首页 > 解决方案 > dispatch 没有更新 reducer

问题描述

我正在使用 useReducer 和 useContext 作为通量存储,我很困惑为什么我无法更新存储状态。这是我正在使用的代码示例。

减速器和初始状态

export const localState = {
 modal_open: false,
 date: null
}

export const reducer = (state , action) => {
switch (action.type) {
  case "OPEN_MODAL":
    return {
      ...state,
      modal_open: true
      
    }
    case "CLOSE_MODAL":
    return {
      ...state,
      modal_open: false
    }
    case "SET_DATE":
    return {
      ...state,
      date: action.payload
    }
  default:
    return state;
}

};

上下文构造函数和组件包装 import React from "react";

  const LocalWebSiteContext= React.createContext();


    const WebsiteDetails = () => {
     const [state, dispatch] = React.useReducer(reducer, localState)
     const [averPositions, setAverPositions] = React.useState()
     const classes = useStyles();
     let match = useRouteMatch("/app/websites/:id/:slug");
     let { id } = useParams();
     const context = useContext(UserContext);
     const history = useHistory();

       //testing
       const { localContext } = context

  
       const websiteData = localContext.websites.find((el, idx) => {

       if(el.website_id === id){
         return el;
        }
      });
  
      const userAndWebsiteData = {
       ...websiteData,
       ...localContext.user
     }

     if(!userAndWebsiteData){
       console.log('Not a valid website');
       history.push('/app/websites/');
       // return;
     }




  return (
     <>
      <localWebSiteContext.Provider value={{state, dispatch}}>
      { userAndWebsiteData && 
      <Page className={classes.root} title="Analytics Dashboard">
      {/* { JSON.stringify(userAndWebsiteData) }
      { id } */}
        <Header websiteData={userAndWebsiteData} />
        <Grid className={classes.container} container spacing={3}>
          <Grid item xs={12}>
            <Overview websiteData={userAndWebsiteData} />
          </Grid>
          <Grid item lg={8} xl={9} xs={12}>
            <CustomModal />
            <FinancialStats websiteData={userAndWebsiteData}/>
          </Grid>
          <Grid item lg={4} xl={3} xs={12}>
            {/* { 
          JSON.stringify(userAndWebsiteData.positionRangesData)} 
          */}
          <Top5To30 positionData={userAndWebsiteData.positionRangesData 
           ? userAndWebsiteData.positionRangesData : {} } />
          range bar chart
          <EarningsSegmentation />
          </Grid>
          <Grid item lg={12} xs={12}>
            <KeywordsList /> 
          </Grid>
          <Grid item lg={4} xs={12}>
            <CustomerActivity />
          </Grid> 
        </Grid>
      </Page>
      }
    </localWebSiteContext.Provider>
  </>
  );
};

我正在调度有效负载以更改日期的组件

 const FinancialStats = props => {
 const {state, dispatch} = React.useContext(localWebSiteContext)
const { websiteData, className, handleAverData, ...rest } = props;
const [dateId, setDateId] = React.useState(null)

const [disabled, setDisabled] = useState([]);
const handleModalOpen = () => {
const averPositions = websiteData.dailyAveragePositions;
if (averPositions){
  const dateNum = parseInt(averPositions[0].d)
  dispatch({type: 'OPEN_MODAL', payload: dateNum})
  }
}

      return (
        <span
          key={dataKey}
          className="legend-item"
          style={style}
        >
          <Surface width={10} height={10}>
            <Symbols cx={5} cy={5} type="circle" size={50} fill={color} />
            {active && (
              <Symbols
                cx={5}
                cy={5}
                type="circle"
                size={25}
                fill={'#FFF'}
              />
            )}
          </Surface>
          <span>{dataKey}</span>
        </span>
      );
    })}
  </div>
);

};

预期的行为是当我 dispatch({type: 'SET_DATE', payload: dateNum) 时,它将反映所有其他组件都订阅了 useContext 钩子。但我不能为我的生活让它从 null 更新......我能够切换 bool 值。即使我尝试在 useState 挂钩中本地设置它仍然为空?也许与渲染有关?提前致谢!!

标签: javascriptreactjsreact-hooksuse-reducer

解决方案


推荐阅读