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

时间:2020-06-09 05:24:54

标签: javascript reactjs react-hooks

如何从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 (

  );
};

3 个答案:

答案 0 :(得分:2)

您应该添加标题作为useEffect的依赖项,并使用title而不是newTitle更新状态。同样,原始状态需要设置为title,而不是Title

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

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

  return (

  );
};

P.S。这也是一种反模式,当状态可以直接从道具派生时,可以将道具复制到状态中,除非您需要在本地修改状态。

答案 1 :(得分:0)

对于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 (

  );
};

答案 2 :(得分:0)

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

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

  return (

  );
};

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