gpt4 book ai didi

javascript - 为什么页面重渲染需要传入this.state.example?

转载 作者:行者123 更新时间:2023-11-30 11:06:27 24 4
gpt4 key购买 nike

我的渲染中有这个:

{this.availProps(this.state.data)}

this.state.data 在 componentOnMount 时通过获取更新

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>
)
}

这是行不通的。它会打印出“hello”。

这是因为只有在“渲染”中的变量发生更改/更新时才会重新渲染页面吗? (在本例中为 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 上设置属性不会调用 render 方法。

您将必须使用 this.setState({ useData: useData }) 以便对运行渲染方法的某些更改使用react。

并且由于正在设置的状态基于之前的状态,因此您最好使用状态更新器模式及其回调,以便在您尝试访问更新后的状态时可用。

Do not update state directly

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)
})
})
}

关于javascript - 为什么页面重渲染需要传入this.state.example?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55424709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com