问题描述
React中的上下文和约简工具是全新的。我目前正在尝试使用上下文从折线图上的事件获取日期字符串。我正在使用的折线图来自react-chartjs-2。
我的上下文已设置并提供如下:
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>
然后,我的线图组件将通过以下方式导入上下文:
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,1)',borderColor: 'rgba(0,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不是函数
任何对此的帮助将不胜感激。
解决方法
您要将对象传递给Context provider,因此需要相应地对其进行破坏:
<Context.Provider value={{ state,dispatch }}> ...</Context.Provider>
const { state,dispatch } = useContext(Context)
// Same
const value = useContext(Context)
value.dispatch(...)