reactjs - 如何将 this.setState({ [section]: y }) 转换为 useState 钩子?
问题描述
我只是将我的类转换为函数组件。我想在一个函数中转换为状态。
constructor() {
super();
this.state = {
sections: [1, 2, 3, 4, 5, 6, 7, 8],
currentSection: 1
};
}
onItemLayout = ({ nativeEvent: { layout: { x, y, width, height } } }, section) => {
// setting each items position
this.setState({ [section]: y });
};
我刚刚将状态转换为
const [sections] = useState([1, 2, 3, 4, 5, 6, 7, 8]);
const [currentSection, setCurrentSection] = useState(1);
但无法理解如何转换
this.setState({ [section]: y });
到功能组件。
解决方案
const [state, setState] = useState({
sections: [1, 2, 3, 4, 5, 6, 7, 8],
currentSection: 1
});
const onItemLayout = ({ nativeEvent: { layout: { y } } }, section) => {
setState(currentState => ({
...currentState,
[section]: y
}))
};
const updateSection = (newSection) => {
setState(currentState => ({
...currentState,
currentSection: newSection
}))
};
推荐阅读
- php - PHP中的类型检查?
- nginx - 如何在 nginx 中为服务器错误和超时设置 json 响应
- string - 为什么我不能将 Lines 迭代器收集到字符串向量中?
- ios - UIButton 背景图片可以支持动态类型吗?
- excel - Excel - 使用多个条件计算唯一值
- javascript - SVG 元素事件
- javascript - React/NodeJS - 访问 localhost:3000 时网页无法正常工作
- google-maps - 谷歌自动完成多边形作为 GeoJson
- java - 使用 Gradle 5.0 进行集成测试
- typescript - 如何在 TypeScript 中正确进行递归类型定义?