[英]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.