我一直在尝试将我的减速器与我的上下文提供程序维护在同一个文件中。但是,我无法弄清楚如何在组件文件中使用它。
在我的 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>
)
在表单内部的组件处:我怀疑我没有正确使用调度,但无法通过谷歌搜索解决它
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>