[英]React setState doesn't update
I saw thousands post about it so I am a bit confuse, I did use arrow function, I binded my method changed for componentDidUpdate but I still can't manage to我看到成千上万的帖子,所以我有点困惑,我确实使用了箭头 function,我绑定了我的方法更改为 componentDidUpdate 但我仍然无法设法
in my async call setState my data and pass it to my child component.在我的异步调用 setState 我的数据并将其传递给我的子组件。
ParentComponent父组件
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
activeNav: 1,
loading: true,
data: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData = () => {
var that = this;
getMyData()
.then(res => {
console.log(res); // Output res Object
that.setState({
data: res
})
})
.catch((error) => {
console.log(error);
});
}
componentDidUpdate = () => this.fetchData()
render() {
const { data, loading } = this.state;
return (
<>
<ChildComponent data={this.data} loading={loading}/>
</>
);
}
}
ChildComponent子组件
class CurrentUp extends React.Component {
constructor(props) {
super(props);
}
componentDidUpdate = () => {
console.log(this.props.data); // Output []
console.log(this.props.loading); // Output true
}
}
render() {
console.log(this.props.data); // Output []
console.log(this.props.loading); // Output true
return (
<div>
</div>
);
}
}
What am I missing?我错过了什么?
Solved , i am not sure how.解决了,不知道怎么解决。 I kept trying different stuff
我一直在尝试不同的东西
You are console logging the data in the componentDidMount
method.您正在控制台记录
componentDidMount
方法中的数据。 This method runs only once when a component is mounted.此方法仅在安装组件时运行一次。 When you update the data in the parent component, and pass it to the child component, it doesn't re-create the entire component instance.
当您更新父组件中的数据并将其传递给子组件时,它不会重新创建整个组件实例。 Only the updates are passed down.
仅传递更新。 You can access those updates in
componentDidUpdate
method.您可以在
componentDidUpdate
方法中访问这些更新。 Or, if you are directly accessing props, you can log the data inside the render
method.或者,如果你直接访问 props,你可以在
render
方法中记录数据。
class CurrentUp extends React.Component {
constructor(props) {
super(props);
}
render = () => {
console.log(this.props.data);
console.log(this.props.loading);
return null;
}
}
Other points:其他要点:
this
if you are using an arrow function.this
绑定。this
keyword.this
关键字是安全的。 No need of assigning it to that
.that
。Try to bring some more code cause I see the child component you posted is an instead current up component.尝试带来更多代码,因为我看到您发布的子组件是一个当前向上的组件。 Send the real child component and then move the var in your fetchData function to the constructor.
发送真正的子组件,然后将 fetchData function 中的 var 移动到构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.