我正在尝试等待 componentDidMount
中的数据然后改变我的状态isLoading
为 false 但setState
没有触发。我能够 console.log branch.init
内的数据但我不知道为什么setState
不工作。
state = {
isLoading: true,
}
componentDidMount() {
console.log("componentDidMount");
let branchKeyTest = 'key_test_aBcDeF'
branch.init(branchKeyTest, function(err, data) {
console.log(JSON.stringify(data, null, 1))
this.setState({ isLoading: false })
if (data && data.data_parsed) {
switch (data.data_parsed.link_type) {
case 'new_release':
localStorage.setItem('redirect', JSON.stringify({
'link_type': 'new_release',
'release_id': data.data_parsed.release_id
}));
break;
default:
console.log("do nothing")
}
}
})
}
render() {
const { isLoading } = this.state;
if (!isLoading) {
return (
<div>Done Loading</div>
)
else {
return (
<div>Still Loading</div>
)
}
}
最佳答案
branch.init(branchKeyTest, function(err, data) {
需要更改为 branch.init(branchKeyTest, (err, data) => {
因为您无权访问匿名函数内类的 this
关键字。
按照您编写的方式,您无权访问 this
,因为 this
引用的是函数的上下文 - 而不是类。通过将其更改为粗箭头语法,您可以访问 React 类的上下文的 this
。
您可以阅读有关 this here 的更多信息.
关于javascript - 在 componentDidMount 中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59380682/