javascript - 反应数组状态在渲染之前被清除
问题描述
有响应问题。
当进行 ajax 调用以从后端检索数据时,我检索数据,但似乎它仅在将数据包装在.then()
. 在 a .then()
then 之外,数据将被清除。
consume 是一个处理 axios 调用的个人模块。
这是问题
componentWillMount() {
const retrieveLogs = {
method: "GET",
url: this.state.url,
}
consume.fetch(retrieveLogs)
.then(res => {
if(typeof res.logger === "object"){
this.setState({
logs: res.logger,
})
console.log(this.state.logs) // show the console log here but
}
})
console.log(this.state.logs) // but shows empty array here why is this ?
}
解决方案
componentWillMount
不安全且已弃用,您不应使用它,请参阅此处的详细信息。最好的方法是用来componentDidMount
获取你的数据,然后更新状态。具有空状态的初始渲染是模式,您不必担心。此外,您不应该像那样记录您的状态,记住,setState
它是异步的,并且您不能保证在调用时会更新状态console.log
,在这种情况下,使用它的第二个参数setState
为您提供一个回调,只有在所有更新完成时才会触发.
componentDidMount() {
const retrieveLogs = {
method: "GET",
url: this.state.url,
}
consume.fetch(retrieveLogs)
.then(res => {
if(typeof res.logger === "object"){
this.setState({
logs: res.logger,
}, console.log(this.state.logs))
}
})}
如果您需要在数据到达后执行一些操作,componentDidUpdate
请在 props 或 state 发生变化时使用来实现您的自定义逻辑。
componentDidUpdate(prevProps, prevState){
if(prevProps.item !== this.props.item)
this.setState({item}, console.log(this.state.item))
}
推荐阅读
- jquery - Jquery替代mailto链接与html正文
- android - 奥利奥(8.1)上的吐司重叠问题
- javascript - JS Promises - 为什么我看到 UnhandledPromiseRejectionWarning 和 DeprecationWarning?
- javascript - 在聚合调用中限制字段属性的更好方法
- ms-access - TempVars - 获取 ID 以在下一个表单中使用
- javascript - Webpack 监视文件更改并触发其他文件的加载器
- php - 这个 PHP 伪 DI 模式是错误的/危险的吗?
- vue.js - v-select 与过滤剂量工作
- architecture - 从 N 层转换为 DDD
- kurento - Coturn 服务器不完整的日志