Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript (良好编程实践)渲染中的两个返回是否正确?_Javascript_React Native_Axios - Fatal编程技术网

Javascript (良好编程实践)渲染中的两个返回是否正确?

Javascript (良好编程实践)渲染中的两个返回是否正确?,javascript,react-native,axios,Javascript,React Native,Axios,下面的代码工作得很好,我只想知道我这样做是否最正确,因为有两条返回指令,第二条在本文中的arrow函数范围内,可以删除,因为它只返回一个元素,但当我删除时,我的列表不会呈现 componentWillMount() { axios.get('http://api.tvmaze.com/search/shows?q=Vikings') .then((response) => { // handle success this.setSt

下面的代码工作得很好,我只想知道我这样做是否最正确,因为有两条返回指令,第二条在本文中的arrow函数范围内,可以删除,因为它只返回一个元素,但当我删除时,我的列表不会呈现


  componentWillMount() {
    axios.get('http://api.tvmaze.com/search/shows?q=Vikings')
      .then((response) => {
        // handle success
        this.setState({ listaItens: response.data })
        //console.log(response);
      })
      .catch(() => {
        // handle error
        console.log("Erro ao recuperar dados");
      })
  }


  render() {
    return (
      <View>
        {this.state.listaItens.map(item => {
          return (
            <Text key={item.show.id}>{item.show.name}</Text>
          );
        })}
      </View>
    )
  }

组件willmount(){
axios.get()http://api.tvmaze.com/search/shows?q=Vikings')
。然后((响应)=>{
//成功
this.setState({listaItens:response.data})
//控制台日志(响应);
})
.catch(()=>{
//处理错误
控制台日志(“Erro ao重现护墙板”);
})
}
render(){
返回(
{this.state.listaItens.map(项=>{
返回(
{item.show.name}
);
})}
)
}

第二个返回值用于
.map
数组方法,这是必需的。由于
.map
返回一个新数组,因此必须返回正在迭代的原始数组的元素

基本上你可以这样做:

render(){
返回(
{
[
{this.state.listaItens[0].show.name},
{this.state.listaItens[1].show.name},
{this.state.listaItens[2].show.name},
{this.state.listaItens[3].show.name}
]
}
)

}
这两个返回语句不在同一个函数中。其中一个在回调的内部范围内,而另一个实际上是从渲染方法返回的。如果您想知道是否应该为了可读性而以不同的方式编写,我将提出以下建议:

render(){
返回(
{this.state.listaItens.map(item=>{item.show.name}}
);
}
如果只有一条语句(),lamba表达式允许省略return语句。我必须指出,你现在所做的既不是错误的,也不是不好的做法