【发布时间】:2020-10-18 13:30:41
【问题描述】:
我为按钮切换创建了一个示例。
这是由useContext(存储数据)和useReducer(处理数据)完成的。它工作正常。
这是CodeSandBox Link 的工作原理。
version 1 只是在单击按钮时调度。
然后我创建了一个切换的version 2。基本上只是将调度放在自定义钩子中。但不知何故,它不起作用。
// context
export const initialState = { status: false }
export const AppContext = createContext({
state: initialState,
dispatch: React.dispatch
})
// reducer
const reducer = (state, action) => {
switch (action.type) {
case 'TOGGLE':
return {
...state,
status: action.payload
}
default:
return state
}
}
//custom hook
const useDispatch = () => {
const {state, dispatch} = useContext(AppContext)
return {
toggle: dispatch({type: 'UPDATE', payload: !state.status})
// I tried to do toggle: () => dispatch(...) as well
}
}
// component to display and interact
const Panel = () => {
const {state, dispatch} = useContext(AppContext)
// use custom hook
const { toggle } = useDispatch()
const handleChange1 = () => dispatch({type: 'TOGGLE', payload: !state.status})
const handleChange2 = toggle // ERROR!!!
// and I tried handleChange2 = () => toggle, or, handleChange2 = () => toggle(), or handleChange2 = toggle()
return (
<div>
<p>{ state.status ? 'On' : 'Off' }</p>
<button onClick={handleChange1}>change version 1</button>
<button onClick={handleChange2}>change version 2</button>
</div>
)
}
// root
export default function App() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<AppContext.Provider value={{state, dispatch}}>
<div className="App">
<Panel />
</div>
</AppContext.Provider>
);
}
不确定那里发生了什么。但我认为调度状态有问题。
(我试过如果有效载荷没有处理状态,就像一些硬代码一样,所以此时应该触发调度)
有人可以帮帮我吗?欣赏!!!
【问题讨论】:
标签: javascript reactjs react-hooks use-reducer use-context