reactjs - 如何将设置状态抛出到全局变量
问题描述
我想将值扔给 const countBadge,但我遇到了未定义的错误。我如何能够将我获取的数据设置为全局变量?我需要导出新值
数据的获取是正确的,因为在另一部分我 console.log 结果 [0].NumToApprove 并且它的值为 7。
const countBadge = this.state.numToApprove
class Notifications extends Component{
constructor(props){
super(props);
this.state = {
numToApprove: 0,
}
}
fetchData = () =>{
fetch(APILink + '/filing/get_badges', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: qs.stringify({
'is_from_api': true
})
})
.then(response => response.json())
.then((result) => {
this.setState({
numToApprove: result[0].NumToApprove
})
}).catch(error => {
alert('Transaction Error' + error)
}
);
}
}
export { countBadge }
解决方案
因此,首先,您在this
组件外部使用它不会评估您的组件,因此countBadge
不会保留numToApprove
组件中的那个。
然后,如果你想改变它的值,你应该使用let
and not const
。
所以这样的事情应该做:
let countBadge = 0
class Notifications extends Component{
constructor(props){
super(props);
this.state = {
numToApprove: 0,
}
}
fetchData = () =>{
fetch(APILink + '/filing/get_badges', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: qs.stringify({
'is_from_api': true
})
})
.then(response => response.json())
.then((result) => {
this.setState({
numToApprove: result[0].NumToApprove
})
countBadge = /* ... the new value ... */
}).catch(error => {
alert('Transaction Error' + error)
}
);
}
}
export { countBadge }
那么,如果你想让另一个组件一旦countBadge
改变就更新,解决方法是不要把它作为一个全局变量,因为全局变量在改变时不会触发 UI 更新。相反,有两种解决方案:
- 置于和其他组件
countBadge
最近的共同祖先的状态Notifications
- 使用 Redux
推荐阅读
- docker - 使用 mssql-tools 登录 Docker 失败
- youtube-api - 指定收件人 Youtube api v3 插入评论
- image - Graphviz 不渲染节点图像
- shell - 使用 shell 脚本替换 JSON 文件中 char 的第一个实例
- oracle - Oracle:调用中的参数数量或类型错误
- php - 如何在网站前端按 SKU 搜索产品
- javascript - 如何用 jest 模拟和测试链式函数?
- bash - 为什么 bash 不在 $() 运算符中拆分字段?
- node.js - 是否可以从 PM2 获取流程元数据?
- c++ - 为什么在此代码中隐式转换为常量迭代器会失败?