【问题标题】:How do I get the new updated data from react hooks or useEffect?如何从 react hooks 或 useEffect 获取新的更新数据?
【发布时间】:2020-09-28 05:12:02
【问题描述】:

如何从 react hooks 或 useEffect 获取最新更新的数据?

我加载了标题为Shoes 的父组件,然后将输入更改为"New Shoes",但我的子组件中的数据没有改变,它仍然是"Shoes"。如何更新?

在父组件中:

<UrlInput
   value={url}
   title={title}
   baseURL={baseURL}
   onChange={this.onURLChange}
/>

子组件

const UrlInput = ({title}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(newTitle)
     })

  return (

  );
};

【问题讨论】:

  • 为什么你的useState构造函数中的title变量是大写的?

标签: javascript reactjs react-hooks


【解决方案1】:

您应该将 title 作为依赖项添加到 useEffect 并使用 title 而不是 newTitle 更新状态。原始状态也需要设置为title 而不是Title

const UrlInput = ({title}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(title)
     }, [title]);

  return (

  );
};

附:当 state 可以直接从 props 派生时,它也是一种将 props 复制到 state 中的反模式,除非您需要在本地修改 state。

【讨论】:

  • 您能分享一下您是如何在父级中更新标题的吗?它是否会触发子级中的重新渲染
【解决方案2】:
const UrlInput = ({title, ...rest}) => {
    const [newTitle, setTitle] = useState(title);

     useEffect(() => {
         console.log(title)
         setTitle(title)
     },[title]) 

  return (

  );
};

尝试用上面的代码替换代码。您应该将一个新值传递给 setTitle() 您传递的变量与存储先前值的变量相同。

【讨论】:

    【解决方案3】:

    对于 get,组件中任何特定于状态的更改都使用 useEffect(() => {},[这里的特定条件])。

    您可以在此处关注此代码。

    在父组件中:

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

    子组件

    const UrlInput =props => {
        const [newTitle, setTitle] = useState(props.Title);
    
         useEffect(() => {
             console.log(title)
             setTitle(newTitle)
         },[props.Title])
    
      return (
    
      );
    };
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2020-04-09
      • 2020-11-28
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多