javascript - 如何在 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)}
)
解决方案
功能组件是无实例的,因此,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];
推荐阅读
- regex - 将 .htaccess 中的 URL 编码 (%20) 替换为 +
- javascript - 如何用javascript替换函数替换字符串第一个之后的所有句点?
- three.js - 如何放大光线投射器选择?
- reactjs - 每当我将 id 从孩子发送给父母时,我都会变得不确定,我可以知道我错过了什么吗?
- android - Google Play 商店无法上传带有“被 CORS 策略阻止”错误的应用程序图标
- javascript - 带有提示符和 || 的 if/else 语句
- java - 文档中的数组未映射到 java pojo 对象中的列表
- kendo-ui - 剑道工具提示仅在第二个“悬停”事件后显示
- python - 如何计算 Django 的总工作时间?
- excel - VBA隐藏/取消隐藏活动单元格下方的3行