【问题标题】:state is empty in first render第一次渲染时状态为空
【发布时间】:2017-02-14 14:56:21
【问题描述】:

以下代码给了我这个错误:“无法读取未定义的属性'CityName'”。但是当我调试代码时,数据状态仅在第一次渲染时为空,并且在该数据从 API 接收到数据之后。有没有办法强制渲染忽略第一个空状态?

  class profile extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data :[],
        };
       }
    
    componentWillMount() {
        axios.get(BASE_URL + 'user/' + 1)
            .then(response => this.setState({data: response.data.Result}))
            .catch(error => console.log(error));
    }
    
    render() {
         return (
             <View>
                <Text>{this.state.data.Profile.CityName}</Text>
             </View>
         );
      }
    }

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    在第一个渲染中,this.state.data 是一个空数组,因此您应该在您的 render 方法上放置一个控件,假设您的网络调用返回一个数组:

    render() {
          const {data = []} = this.state;
             return (
                 data.map((record, index) => <View key={index}>
                                       <Text>{record.Profile.CityName}</Text>
                                     </View>)
             );
          }
        }
    

    否则如果你的网络请求返回一个对象,那么它应该是这样的:

    render() {
              //You may like to show loading indicator while retrieving data:
              const {data = undefined} = this.state;
                 if(data) {
                     return (
                           <View>
                             <Text>{this.state.data.Profile.CityName}</Text>
                           </View>
                     );
                 }else{
                     return <View><Text>Is loading</Text></View>
                 }
    
            }
    

    【讨论】:

    • 非常好用。但我仍然不明白 const {data = undefined} = this.state 到底在做什么。
    • 这是 ES6 的 destructuring 特性。本质上它与const data = this.state.data 相同,因此只是将对象的字段显式分配给变量的较短版本。
    【解决方案2】:

    您已将data 定义为空数组,然后将其分配给对象。不要将其初始化为空数组,而是将其初始化为null。

    class profile extends Component {
    
    constructor(props) {
        super(props);
        this.state = {
            data :null,
        };
       }
    
    componentWillMount() {
        axios.get(BASE_URL + 'user/' + 1)
            .then(response => this.setState({data: response.data.Result}))
            .catch(error => console.log(error));
    }
    
    render() {
         return (
             <View>
                {this.state.data !== null ? <Text>{this.state.data.Profile.CityName}</Text> : <Text>Please Wait</Text>}
             </View>
         );
      }
    }
    

    【讨论】:

    • 我猜你打错了,渲染方法应该使用this.state.data而不是this.props.data
    • 对不起,但它给了我同样的错误。 @cubbuk 代码解决了我的问题。
    • @nrgwsth 嘿,如果我有一些文本输入,并且该值基于 this.state.data.something 的值,如何避免没有错误,例如 TextInput 值必须不为空!
    • ` { this.setState(Object.assign(data, { username: username })) }} />`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多