Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.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
Reactjs 在成功的ajax调用设置状态之前,使用初始状态对父级渲染进行反应_Reactjs_Webpack - Fatal编程技术网

Reactjs 在成功的ajax调用设置状态之前,使用初始状态对父级渲染进行反应

Reactjs 在成功的ajax调用设置状态之前,使用初始状态对父级渲染进行反应,reactjs,webpack,Reactjs,Webpack,我正在使用React with webpack和babel编译jsx。我的父组件如下所示: const Menu = module.exports = React.createClass({ loadUser() { let xhr = new XMLHttpRequest(); xhr.open('GET', this.state.url, true); xhr.onload = function() { let

我正在使用React with webpack和babel编译jsx。我的父组件如下所示:

const Menu = module.exports = React.createClass({
    loadUser() {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', this.state.url, true);
        xhr.onload = function() {
            let data = JSON.parse(xhr.responseText);
            this.setState({
                user: data
            });
        }.bind(this);
        xhr.send();
     },

     componentDidMount() {
         this.loadUser();
     },

     getInitialState() {
         return {
             url: this.props.url,
             user: []
         };
     },

    render: function() {

        return (
            <div className="menu">
                 <Nav user={this.state.user} />
                      ...
            </div>
        );
    }

});
const菜单=module.exports=React.createClass({
loadUser(){
设xhr=newXMLHttpRequest();
xhr.open('GET',this.state.url,true);
xhr.onload=函数(){
让data=JSON.parse(xhr.responseText);
这是我的国家({
用户:数据
});
}.约束(本);
xhr.send();
},
componentDidMount(){
this.loadUser();
},
getInitialState(){
返回{
url:this.props.url,
用户:[]
};
},
render:function(){
返回(
...
);
}
});
如您所见,我尝试使用
this.setState(…)
this.state.user
设置为从XMLHttpRequest接收的数据。但是,当我尝试在子对象中访问它时,
Nav
,只需调用
console.log(this.props.user)
,只打印一个空数组,即
[]


我做错了什么?我读了React的文件,我被难住了。在下面的例子中,数据是从服务器获取的,并以类似于我(上面)所做的方式传输到子组件。任何帮助都将不胜感激。如果我需要提供任何额外的代码或上下文,请告诉我。谢谢。

getInitialState在第一次渲染时使用,因此在ajax调用之前完成是正常的,因为ajax调用是在ComponentDidMount中执行的,而ComponentDidMount是在第一次渲染之后触发的

在ajax调用为空之前,state.user将为空,然后当收到数据时,它应该使用新数据更新视图

在我看来,你没有做错什么,这取决于你想做什么。 例如,您可以在getinitialstate中放置一条消息,如mgs:“请等待数据正在提取”,并在数据到达时删除此消息

否则,如果绝对需要在呈现组件之前准备好数据,则可以使用:请仔细阅读,它可能不适合您的使用


就我个人而言,我会在getinitialstate中添加一条消息,然后按照您的方式进行操作。

谢谢您的帮助。我想这就是我要走的方向。