[英]Passing updated state from parent to child
I create a let variable in my parent component with the boolean false.我用 boolean false 在我的父组件中创建了一个 let 变量。 I pass that variable as a prop to the child component.我将该变量作为道具传递给子组件。 I change the variable to true through a function in the parent component.我通过父组件中的 function 将变量更改为 true。 My problem is that the value of the prop in the child component is still false when I console.log it afterwards.我的问题是当我 console.log 之后子组件中 prop 的值仍然是 false 。
Parent:家长:
function App() {
let success = false
const changePW = async ({password, repeatPW}) => {
success = true
console.log(`Success App0: ${success}`)
console.log('ChangePW')
return (
<BrowserRouter>
<div className="container">
<Header/>
<Route path='/' exact render={(props) => (
<>
<AddPasswort onChange = {changePW} success = {success}/>
<Footer />
</>
)}/>
<Route path='/about' component={About} />
<Route path='/success' component={Success} />
<Route path='/error' component={Error} />
</div>
</BrowserRouter>
);
}
export default App;
Child孩子
const AddPasswort = ({onChange,success}) => {
const[password, setPassword] = useState('')
const[repeatPW, setRepeatPW] = useState('')
// create a history object
const history = useHistory()
const onSubmit = async (e) => {
e.preventDefault();
await onChange({password, repeatPW})
console.log(success)
// navigate to the success page
if (success){
console.log('success')
history.push("/success")
}
else{
console.log('error')
history.push("/error")
}
}
}
...
}
export default withRouter(AddPasswort);
I thought the problem was that the function does not wait for onChange to finish so I made it asynch, but that did not resolve the issue我认为问题是 function 不等待 onChange 完成所以我让它异步,但这并没有解决问题
because success is not a state, only changing state will re-render component.因为success不是state,只有改变state才会重新渲染组件。 try尝试
const [success, setSuccess] = useState(false);
to change the value of success to true, do要将成功的值更改为 true,请执行
setState(true)
this should solve your problem这应该可以解决您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.