![](/img/trans.png)
[英]How to dispatch action in Custom Hooks by useReducer and useContext?
[英]How to properly use useReducer with useContext?
我一直试图在与我的上下文提供程序相同的文件中维护我的减速器。 但是,我一直无法弄清楚如何在组件文件中使用它。
在我的 Context 函数内部:
const reducer = (state, action) => {
switch (action.type) {
case "SET_LOCATION":
return {...state, location: action.payload}
case "SET_BUSINESS":
return {...state, business: action.payload}
case "SET_DATE":
return {...state, date: action.payload}
default:
return state
}
}
const [{location, business, date}, dispatch] = useReducer(reducer, {
location: "",
business: "",
date: "today",
})
return (
<ThemeContext.Provider value={{location, business, date, dispatch, reducer}}>
{props.children}
</ThemeContext.Provider>
)
在表单内的组件中:我怀疑我没有正确使用 dispatch,但无法通过谷歌搜索来解决它
const {location, business, date, dispatch, reducer} = useContext(ThemeContext)
return (
<form className="booking-form">
<h1>Book a service</h1>
<label>
Location
<input
type="text"
name="location"
value={location}
onChange={() => dispatch("SET_LOCATION")}
/>
</label>
<br/>
<br/>
<label>
Business
<input
type="text"
name="business"
value={business}
onChange={() => dispatch("SET_BUSINESS")}
/>
</label>
<h2 className="date">Date</h2>
<label>
<input
type="radio"
name="date"
value="today"
checked={date === "today"}
onChange={() => dispatch("SET_DATE")}
/>
Today
</label>
<label>
<input
type="radio"
name="date"
value="tomorrow"
checked={date === "tomorrow"}
onChange={() => dispatch("SET_DATE")}
/>
Tomorrow
</label>
<label>
<input
type="radio"
name="date"
value="other"
checked={date === "other"}
onChange={() => dispatch("SET_DATE")}
/>
Different date
</label>
{date === "other" ? <Calendar/> : <TimeGrid/>}
</form>
您的减速器希望收到一个字段type
为的对象:
const reducer = (state, action) => {
switch (action.type) {
// we're checking field type here
...
}
但你只是传递字符串:
() => dispatch("SET_DATE")
您需要调度具有预期结构的操作对象,因为您的减速器将接收dispatch()
方法的参数作为第二个参数:
() => dispatch({ type: 'SET_DATE', payload: ... })
您还需要提供一些有效负载,因为您的减速器期望它:
const reducer = (state, action) => {
return {...state, date: action.payload}
// here we expect payload field on action object
}
还有一项改进 - 请从组件中提取您的减速器,因为它是一种静态纯函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.