javascript - 为什么需要传入 this.state.example 来重新渲染页面?
问题描述
我的渲染中有这个:
{this.availProps(this.state.data)}
this.state.data
在 componentOnMount 时使用 fetch 更新
availProps = data =>{
if (data.length == 0)
return (
<option>"hello"</option>
)
else
return (
<option> "hi" </option>
)
}
数据提取完成后,它会很好地打印出“hi”。但是,如果我使用:
{this.availProps()}
和
availProps = () =>{
if (this.state.data.length == 0)
return (
<option>"hello"</option>
)
else
return (
<option> "hi" </option>
)
}
不起作用。它会打印出“你好”。
这是因为只有在“渲染”中的变量更改/更新时才会重新渲染页面?(在这种情况下,this.state.data)
谢谢
编辑:这是componentDidMount
componentDidMount() {
this.getDataFromDb()
}
getDataFromDb = () => {
fetch("http://localhost:3001/api/property")
.then(property => property.json())
.then(res => this.setState({ data: res.data }))
.then(() =>{
for(var i = 0; i < this.state.data.length; i++) {
if (this.state.data[i].status == 0)
this.state.useData.push(this.state.data[i])
}
}).then
( ()=> console.log(this.state.useData))
};
解决方案
直接设置属性this.state
不会调用渲染方法。
您将不得不使用this.setState({ useData: useData })
,以便对运行渲染方法的某些内容发生变化做出反应。
并且由于正在设置的状态基于先前的状态,因此最好使用状态更新器模式及其回调,以便在尝试访问更新状态时可用。
getDataFromDb = () => {
fetch("http://localhost:3001/api/property")
.then(property => property.json())
.then(res => this.setState({
data: res.data
}))
.then(() => {
// Your computations are based on previous state
// use the updater function to have access to the latest
// state as state updates are asynchronous
this.setState((previousState) => {
const {
data
} = previousState;
// accessing this.state here might have stale data
const updatedUseData = data.reduce((acc, obj) => {
if (obj.status === 0) {
acc.push(obj);
}
return acc;
}, []);
// this will invoke the render again as
// a state is updated
return {
useData: updatedUseData
}
}, () => {
// Use the call back which gets invoked once the state
// is updated
console.log(this.state.useData)
})
})
}
推荐阅读
- ios - 使用 @State 解析为在所有存储属性初始化之前使用的“自我”
- python - matplotlib 不尊重 zorder
- python - Mock.assert_has_calls() 没有按预期工作
- azure-cosmosdb - 更新 CRM 字段时逻辑应用程序出错
- php - php - 克隆输入字段后获取文件数据
- c# - 当手动运行与在服务器上运行时,SSIS 中的 Shell32 GetDetailsOf 调用返回不同的结果
- flutter - 如何在 Flutter 中将 JSON 转换为对象?
- python - 使用 OpenCV(英特尔实感)将相机默认值从深度更改为 rgb
- docker - gRPC-node:当 *Dockerizing* 服务时,请求不通过服务的服务器?[包括截图]
- python - 使用 Cedilla Delimer(Ç) 编写文本文件 - 非键盘可打印字符