[英]Why can I *only* access an object property inside setInterval?
Here's the setup. 这是设置。 In a previous question, I found out that I could pass an object property via state in a child component, then grab that object property with componentDidUpdate. 在上一个问题中,我发现可以通过子组件中的状态传递对象属性,然后使用componentDidUpdate来获取该对象属性。 In this case, both the state and prop are called arrival. 在这种情况下,状态和道具都称为到达。
Here's the basic code... 这是基本代码...
export default class App extends Component {
constructor(){
super();
this.state = {
arrival: {}
}
}
axiosFunc = () => {
axios.get('https://api.warframestat.us/pc').then(results => {
this.setState({
arrival: results.data.voidTrader.activation,
});
setTimeout(this.axiosFunc,1000 * 60);
})
}
componentDidMount() {
this.axiosFunc();
}
}
Now in a child component, I can't access the arrival prop like this... 现在在子组件中,我无法像这样访问到达道具...
componentDidMount(){
console.log(this.props.arrival)
}
But I can put it in componentDidUpdate. 但是我可以将其放在componentDidUpdate中。 I also realized that I can put it in a setInterval, then run that setInterval in componentDidMount. 我还意识到我可以将其放在setInterval中,然后在componentDidMount中运行该setInterval。
componentDidMount() {
this.intervalFunc = setInterval(() => {
console.log(this.props.arrival);
}
, 1000);
} }
Why can I access this.props.arrival after putting it inside setInterval, but not outside of it? 为什么将this.props.arrival放在setInterval内,但不能在setInterval内后再访问呢?
I might be completely wrong, however: I believe your issue is based upon the fact that a React child cannot tell whether its' props have updated or not, which results in the component not re-rendering (and therefore inheriting the props). 但是,我可能完全错了:我相信您的问题是基于以下事实:React子代无法告知其道具是否已更新,这导致组件无法重新渲染(并因此继承了道具)。 Using setInterval
does propmt the component to update every x amount of seconds, however. 但是,使用setInterval
确实会促使组件每x秒钟更新一次。 Try setting the props as state in your child component using componentDidUpdate
like below and see if it works 尝试使用设置道具作为国家在你的子组件componentDidUpdate
像下面,看看它的工作原理
componentDidUpdate(prevProps) {
if (prevProps !== this.props) {
this.setState({arrival: this.props.arrival});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.