在componentdidmount-react上从ajax调用更新状态
我需要从ajax响应更新状态变量。我在下面试过了在componentdidmount-react上从ajax调用更新状态,ajax,reactjs,ecmascript-6,Ajax,Reactjs,Ecmascript 6,我需要从ajax响应更新状态变量。我在下面试过了 componentDidMount() { var parent_object=this; axios.get('/template.php') .then((result)=> { console.log(result.data); parent_object.setState({component_template:resu
componentDidMount() {
var parent_object=this;
axios.get('/template.php')
.then((result)=> {
console.log(result.data);
parent_object.setState({component_template:result.data})//not updating
});
console.log("here");
console.log(this.state.component_template);
}
我可以看到result.data的数组,但状态变量component_模板未更新
我试过了
和
但是没有运气来自:
setState并不总是立即更新组件。它可以批处理更新或将更新推迟到以后。这使得在调用setState之后立即读取This.state成为一个潜在的陷阱。相反,请使用componentDidUpdate或setState回调setStateupdater callback,这两者都保证在应用更新后触发
因此,状态可能正在正确更新,但您的console.log可能无法读取更新的值。尝试使用回调,或从以下位置检查componentDidUpdate内部。:
setState并不总是立即更新组件。它可以批处理更新或将更新推迟到以后。这使得在调用setState之后立即读取This.state成为一个潜在的陷阱。相反,请使用componentDidUpdate或setState回调setStateupdater callback,这两者都保证在应用更新后触发
因此,状态可能正在正确更新,但您的console.log可能无法读取更新的值。尝试使用回调,或检查componentDidUpdate内部。React setState是异步的! 状态值更新后,可以调用回调函数:
componentDidMount() {
axios.get('/template.php')
.then((result)=> {
console.log(result.data);
this.setState({component_template:result.data},()=>{
console.log(this.state.component_template);
})
});
}反应设置状态是异步的! 状态值更新后,可以调用回调函数:
componentDidMount() {
axios.get('/template.php')
.then((result)=> {
console.log(result.data);
this.setState({component_template:result.data},()=>{
console.log(this.state.component_template);
})
});
}react中的setState是一个异步调用。设置状态后的控制台不保证更新的值
将console添加为带有setState的回调,或在render方法内部添加为第一行,以检查更新的状态值 react中的setState是一个异步调用。设置状态后的控制台不保证更新的值 将console添加为带有setState的回调,或在render方法内部添加为第一行,以检查更新的状态值