首页 > 解决方案 > 如何在 React hooks 的 setState() 函数中绑定参数?

问题描述

我有一个国家名称列表,当单击其中一个国家/地区时,所选国家/地区的状态应使用新选择的国家/地区的名称进行更新。然后,此状态会触发 a 中的其他更改useEffect()。的状态pickedCountry在父组件中处理,但setPickedCountry()函数作为道具传递给子组件(创建国家列表)。

当我现在onPress={props.setCountry.bind(this, country.name)}向每个列表项添加 a 时,我收到一条警告:

警告:来自 useState() 和 useReducer() Hooks 的状态更新不支持第二个回调参数。要在渲染后执行副作用,请在组件主体中使用 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)}
)

标签: javascriptreactjsreact-nativereact-hooksstate

解决方案


功能组件是无实例的,因此,this无论如何都不需要做任何绑定。看起来您只是想将国家名称作为新的州值传递,即onPress={() => props.setCountry(country.name)}.

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

或者创建一个 curried 函数处理程序,以便只定义和传递一个处理程序。保存在附件中的国家名称。

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

推荐阅读