简体   繁体   English

反应异步数据(对象)分配给状态时被破坏

[英]React async data (object) getting corrupted while assigned to state

I am fairly new to React and having some issue with data binding. 我对React非常陌生,并且在数据绑定方面遇到了一些问题。 It seems like when I assign an object to another object to another object it gets corrupted and I cannot target using it's key. 似乎当我将一个对象分配给另一个对象到另一个对象时,它已损坏并且无法使用其键作为目标。 I have fiddle set up at http://jsfiddle.net/rexonms/uv7scjb6/ . 我在http://jsfiddle.net/rexonms/uv7scjb6/上设置了小提琴。

Thanks in advance 提前致谢

function getMyData(){
    return {name: 'foo', age: 20};
}

var Header = React.createClass({

        getInitialState: function () {
            return {data:null};
        },

        loadData: function () {
             this.setState({data: getMyData()});
        },

        componentDidMount: function () {
            this.loadData();
        },


        // Render the component
        render: function() {

            return(
                <div>
                    Welcome, {this.state.data.name}
                </div>
            );
        }
    });

React.render(<Header />, document.getElementById('container'));

In the initial state, the state.data is still null and render() fails. 在初始状态下, state.data仍为null,并且render()失败。 The component never gets mounted and the data never gets loaded. 组件永远不会挂载,数据永远不会挂载。

You can update the render method to return a different <div> if the data is null or you should provide a different initial state. 如果数据为null或应提供其他初始状态,则可以更新render方法以返回其他<div>

render: function() {
  if(!this.date.data) {
    return(<div>Loading...</div>);
  }
  return(<div>Welcome, {this.state.data.name}</div>);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM