上下文 - dispatch 不是一个函数 (React)
2020-09-09
2416
对 React 中的 context 和 Reducer 非常陌生。我目前正在尝试使用 Context 从折线图上的事件中获取日期字符串。我使用的折线图来自 react-chartjs-2。
我的 context 设置和提供如下:
export const Context = createContext();
const initialState = {
isShowCarousel: false,
date: null,
coin: null
};
const reducer = (state, action) => {
switch (action.type) {
case "GRAPH_CLICKED":
return {
...state,
isShowCarousel: true,
date: action.payload.date,
coin: action.payload.coin
};
default:
return state;
}
};
export default function LandingPage(props) {
const classes = useStyles();
const [state, dispatch] = useReducer(reducer, initialState);
然后设置提供程序如下:
<div className={classNames(classes.main, classes.mainRaised)}>
<Context.Provider
value={{
state,
dispatch
}}
>
<SectionCryptoPrices />
<NewsCarousel date={state.date} coin={state.coin} />
</Context.Provider>
</div>
然后我的折线图组件通过以下方式导入 Context:
import React, { useContext } from 'react';
import {Line} from 'react-chartjs-2';
import { Context } from "views/CryptoMashup/LandingPage";
function LineGraph (props) {
const dispatch = useContext(Context);
let coin = props.coin;
const state = {
labels: props.rowData.labels,
datasets: [
{
label: 'Price movement for ' + props.coin,
fill: true,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 2,
data: props.rowData.prices
}
]
}
return (
// line graph
<div className="line-graph">
<Line
data={state}
options={{
legend:{
display:true,
position:'bottom'
},
onClick: function(evt, element) {
if(element.length > 0) {
let ind = element[0]._index;
let date = element[0]._xScale.ticks[ind];
let payload = {
date,
coin
}
dispatch({
type: "GRAPH_CLICKED",
payload: payload
})
}
}
}}
/>
</div>
);
}
export default LineGraph;
但是我得到了以下信息:TypeError:dispatch 不是函数
任何帮助都将不胜感激。
1个回答
您正在将一个对象传递给 Context 提供程序,因此您需要相应地销毁它:
<Context.Provider value={{ state, dispatch }}> ...</Context.Provider>
const { state, dispatch } = useContext(Context)
// Same
const value = useContext(Context)
value.dispatch(...)
Dennis Vash
2020-09-09