【发布时间】:2021-01-19 10:47:12
【问题描述】:
我有两种状态要维护:
- 包含要显示的项目列表的数组
- 一个整数(称为索引),表示当前显示数组中的哪些元素。
对于数组,我使用 useReducer 钩子来添加、删除、编辑数组中的元素。 reducer 函数写在函数组件之外。
在这个 reducer 中,我想访问“索引”状态的状态值以了解要修改哪个元素。但是,由于这种状态是在功能组件内。如何做到这一点?
这里是示例代码:
function reducer(state, action){
// Reducer code here
}
function SomeComponent(props){
[allItems, dispatch] = useReducer(reducer,[])
[index,setIndex] = useState(null)
// Use the above index within the reducer
}
【问题讨论】:
标签: javascript reactjs react-hooks