簡體   English   中英

如何在 React hooks 的 setState() function 中綁定參數?

[英]How to bind parameters in React hooks' setState() function?

我有一個國家名稱列表,當點擊其中一個國家時,所選國家的 state 應該更新為新選擇的國家的名稱。 這個 state 然后觸發useEffect()中的其他更改。 pickedCountry 的pickedCountry在父組件中處理,但setPickedCountry() function 作為道具傳遞給子組件(創建國家/地區列表)。

當我現在將onPress={props.setCountry.bind(this, country.name)}添加到每個列表項時,我收到一條警告:

警告:State 來自 useState() 和 useReducer() 掛鈎的更新不支持第二個回調參數。 要在渲染后執行副作用,請使用 useEffect() 在組件主體中聲明它。

現在我不知道useEffect會如何幫助我。 有人可以幫幫我嗎?


這些是我的組件:

國家數據

[
    {
        "name": "Germany",
        "data": [*SOME DATA*]
    },
    {
        "name": "France",
        "data": [*SOME DATA*]
    }, ...
]

父組件

const [pickedCountry, setPickedCountry] = useState(null);

useEffect(() => {
    if (pickedCountry!= null) {
      //Do Something
    }    
  }, [pickedCountry]);

return (
    <Child setPickedCountry={setPickedCountry} />
);

子組件

const [child, setChild] = useState([]);

useEffect(() => {
    const myComponents= [];
    for (country of myData) {
        myComponents.push(
            <TouchableOpacity 
                onPress={props.setCountry.bind(this, country.name)} />
        )
    }
    setChild(myComponents);
}, [someProps];

return (
    {child.map((x) => x)}
)

功能組件是無實例的,因此,無論如何都沒有this可以進行任何綁定。 看起來您只是想將國家名稱作為新的 state 值傳遞,即onPress={() => props.setCountry(country.name)}

useEffect(() => {
  const myComponents= [];
  for (country of myData) {
    myComponents.push(<TouchableOpacity onPress={() => props.setCountry(country.name)} />)
  }
  setChild(myComponents);
}, [someProps];

或者創建一個柯里化的 function 處理程序,以便只定義和傳遞一個處理程序。 附件中保存的國家/地區名稱。

useEffect(() => {
  const myComponents= [];
  const onPressHandler = name => () => props.setCountry(name);
  for (country of myData) {
    myComponents.push(<TouchableOpacity onPress={onPressHandler(country.name)} />)
  }
  setChild(myComponents);
}, [someProps];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM