gpt4 book ai didi

javascript - 无法看到 componentWillMount() 中的数据?

转载 作者:行者123 更新时间:2023-12-03 03:01:55 25 4
gpt4 key购买 nike

我正在做.get()在 Jquery 中请求并更新状态。

我的问题是:

为什么我看不到console.log(this.state.storage)中的数据在componentWillMount()以及 componentDidMount()但我确实在 render() 中得到了输出?

此外,我还需要对获取的数据进行操作,我应该在哪个生命周期中执行此操作?

constructor() {
super();
this.state = {
storage: []
}
}

componentWillMount() {
$.get('data.csv', (data) => this.setState({
storage: data
}));
console.log(this.state.storage); //No Output
}

componentDidMount() {
console.log(this.state.storage); //No Output
}

render() {
return (
<div >{this.state.storage}</div> //Do get the Output
);

最佳答案

this.setState 更新组件状态的方式是异步的; documentation here 。如果您想查看 this.setState 所影响的更改,那么您必须将回调传递给函数调用

此外,您还可以在$.get方法的回调中进行操作,如下所示

constructor() {
super();
this.state = {
storage: []
}
}

myCustomOperations = (data) => {
// do custom operations here with data
}

componentWillMount() {
$.get('data.csv', (data) => {
this.myCustomOperation(data);
this.setState({
storage: data
}, () => {
console.log(this.state.storage); // correct output
// this.myCustomOperation(this.state.storage) // if you want to do the custom operation after the data has been put into the state
});
});
console.log(this.state.storage); //No Output
}

componentDidMount() {
console.log(this.state.storage); //No Output
}

render() {
return (
<div >{this.state.storage}</div> //Do get the Output
);

关于javascript - 无法看到 componentWillMount() 中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47343175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com