Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.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 从React JS中的componentDidMount获取_Reactjs_Fetch - Fatal编程技术网

Reactjs 从React JS中的componentDidMount获取

Reactjs 从React JS中的componentDidMount获取,reactjs,fetch,Reactjs,Fetch,我有一个组件和一个提取行fetchUser={this.fetchUser.bind(this)},我在render方法(例如)中的基本映射之后立即使用它 然而,有人建议我应该把它放在componentDidMount中。但是我该怎么做呢?我不能将fetchUser={this.fetchUser.bind(this)}复制到componentDidMount据我所知,您的组件设置如下: class Parent .... { .... fetchUser(){ ...

我有一个组件
和一个提取行
fetchUser={this.fetchUser.bind(this)}
,我在render方法(例如
)中的
基本映射之后立即使用它


然而,有人建议我应该把它放在
componentDidMount
中。但是我该怎么做呢?我不能将
fetchUser={this.fetchUser.bind(this)}
复制到
componentDidMount

据我所知,您的组件设置如下:

class Parent .... {
    ....
    fetchUser(){ 
    ....
    }

    ....
    render(){
        return ( 
        ...
            <BaseMap fetchUser={this.fetchUser.bind(this)}/>
        ...
        );
    }
}

class BaseMap .... {
    ....
    render(){
        let user = this.props.fetchUser();
        return ( 

            <div> { ...use user here ... }</div>

        );
    }
}
类父级。。。。{
....
fetchUser(){
....
}
....
render(){
报税表(
...
...
);
}
}
类基本映射。。。。{
....
render(){
让user=this.props.fetchUser();
报税表(
{…在此处使用用户…}
);
}
}
如果我错了,请纠正我

建议您做的是将对fetchUser的调用从BaseMap components render方法中取出,并移到其componentDidMount方法。然后将用户存储在组件的状态中,并从那里使用它

class BaseMap .... {
     constructor(props){
        super(props);
        this.state={user:null};
     }

    componentDidMount(){
        let user = this.props.fetchUser();
        this.setState({user:user});
    }

    render(){
        return ( 
            <div> {this.state.user?  
                       ...use user here ...
                        : "loading data"
            }</div>
        );
    }
}
类基本映射。。。。{
建造师(道具){
超级(道具);
this.state={user:null};
}
componentDidMount(){
让user=this.props.fetchUser();
this.setState({user:user});
}
render(){
报税表(
{this.state.user?
…在此处使用用户。。。
:“正在加载数据”
}
);
}
}

将您的
fetchUser
方法移动到
BaseMap
组件,然后将componentDidMount中的方法调用为
this。fetchUser()
。否则,将方法作为道具传递并在目标组件中访问它

您在哪里调用
fetchUser
?你能把
的代码贴出来吗?听起来他们的意思是,在
中,您应该在
componentDidMount
中调用
this.props.fetchUser