[英]How do I get the new updated data from react hooks or useEffect?
How do I get the newly updated data from react hooks or useEffect?如何从 react hooks 或 useEffect 获取新更新的数据?
I loaded the parent components with the title: Shoes
then change the input to "New Shoes"
but the data inside my child components doesn't change, its still "Shoes"
.我用标题加载了父组件:
Shoes
然后将输入更改为"New Shoes"
但我的子组件中的数据没有改变,它仍然是"Shoes"
。 how do I get it updated?如何更新?
in the parent components:在父组件中:
<UrlInput
value={url}
title={title}
baseURL={baseURL}
onChange={this.onURLChange}
/>
Child component子组件
const UrlInput = ({title}) => {
const [newTitle, setTitle] = useState(title);
useEffect(() => {
console.log(title)
setTitle(newTitle)
})
return (
);
};
You should add title as a dependency to useEffect and update state with title
and not newTitle
.您应该将 title 作为依赖项添加到 useEffect 并使用
title
而不是newTitle
。 Also the original state needs to be set with title
and not Title
.此外,原始 state 需要设置为
title
而不是Title
。
const UrlInput = ({title}) => {
const [newTitle, setTitle] = useState(title);
useEffect(() => {
console.log(title)
setTitle(title)
}, [title]);
return (
);
};
PS Also its an antipattern to copy props into state when state is directly derivable from props unless you need to modify the state locally. PS 此外,当 state 可以直接从 props 派生时,将 props 复制到 state 是一种反模式,除非您需要在本地修改 state。
const UrlInput = ({title, ...rest}) => {
const [newTitle, setTitle] = useState(title);
useEffect(() => {
console.log(title)
setTitle(title)
},[title])
return (
);
};
try replacing the code with the above one.You should pass a new value into setTitle() you were passing the same variable that stored the previous value.尝试用上面的代码替换代码。您应该将一个新值传递给 setTitle() 您传递的变量与存储先前值的变量相同。
For the get, any state-specific change in a component use the useEffect(() => {},[specific condition here]).对于 get,组件中任何特定于状态的更改都使用 useEffect(() => {},[这里的特定条件])。
You can follow this code here.您可以在此处遵循此代码。
in the parent components:在父组件中:
const [title, setTitle] = useState(''); // initial state parent
const onURLChange = e => setTitle(e.target.value) ; set state parent from children triger
<UrlInput
value={url}
title={title}
baseURL={baseURL}
onChange={this.onURLChange}
/>
Child component子组件
const UrlInput =props => {
const [newTitle, setTitle] = useState(props.Title);
useEffect(() => {
console.log(title)
setTitle(newTitle)
},[props.Title])
return (
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.