![](/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.