簡體   English   中英

React 組件不使用上下文 API 從全局狀態渲染

[英]React components not rendering from global state using context API

我試圖讓我的子組件尋找全局狀態。 到目前為止,我可以注銷我的全局狀態,我可以看到它已更新,但我的組件沒有使用新值更新。 我沒有收到任何錯誤,但也很難找到一個好的解決方案。 如果在這里有幫助,我有完整的 repo(非常小,只有 1 個組件): https : //github.com/jaysnel/context-api-react

是否有任何原因我的 ChangeColor.js 文件沒有隨着新的狀態變化而更新?

更新顏色.js

import React, { useReducer, useEffect } from 'react'
import { useAppContext } from '../public/context/context'

export default function UpdateColor() {
    let { myGlobaData } = useAppContext();
    const [state, dispatch] = useReducer(reducer, myGlobaData);


    function reducer(state, action) {
        let newState = state.slice();
        console.log(state);
        if(newState !== undefined) {
            switch(action.type) {
                case 'UPDATE_COLOR':
                    newState[0].color = 'green';
                    return newState;
                default:
                    throw new Error();
            }
        }
    }

    return (
        <div>
            <button onClick={() => dispatch({type: 'UPDATE_COLOR'})}>Update Color</button>
        </div>
    )
}

更改顏色.js

import React from 'react'
import { useAppContext } from '../public/context/context'

export default function ChangeColor() {

    const { myGlobaData } = useAppContext();
    console.log("ChangeColor.js", myGlobaData)

    return (
        <div>
            <h2 style={{color: myGlobaData[0].color}}>I Change Colors Based On Global State.</h2>
        </div>
    )
}

上下文.js

import { createContext, useContext } from 'react';


const AppContext = createContext();

export function AppWrapper({ children }) {
    const state = {
      myGlobaData: [
            {
                color: 'red',
                text: 'new text new me'
            }
      ],
    }


    return (
      <AppContext.Provider value={state}>
        {children}
      </AppContext.Provider>
    );
  }
  
  export function useAppContext() {
    return useContext(AppContext);
  }
  

我想,你的問題是你在哪里使用了減速器。 Component ChangeColor.js不知道你在UpdateColor.js里面做什么。 解決方案是,如果將 reducer 放入全局上下文context.js ,然后您必須全局訪問您的 reducer。 我確實使用兩種不同的方法創建並推送到 github 工作示例來使用操作減速器。 工作示例

更新顏色.js

import { useAppContext  } from '../public/context/context'

export default function UpdateColor() {
  const { dispatch } = useAppContext();

  const withPayload = () => {
     dispatch({
       type: 'UPDATE_COLOR_WITH_PAYLOAD',
       payload: {color: 'blue', text: 'new text from updateColor.js'}})
  }
  const intoReducer = () => {
     dispatch({type: 'UPDATE_COLOR_INTO_REDUCER'})
  }

  return (
    <div>
      <button onClick={withPayload}>Update Color with payload</button>
      <button onClick={intoReducer}>Update Color into reducer</button>
    </div>
  )
}

更改顏色.js

import { useAppContext } from '../public/context/context'

export default function ChangeColor() {
  const { state } = useAppContext();

  return (
    <div>
      <h2 style={{color: state.color}}>I Change Colors Based On Global State.</h2>
      <p style={{textAlign: 'center'}}>{state.text}</p>
    </div>
  )   
}

上下文.js

import { createContext, useContext, useReducer } from 'react';

const AppContext = createContext();

export function useAppContext() {
  return useContext(AppContext);
}

function reducer(state, action) {
  switch (action.type) {
    case 'UPDATE_COLOR_WITH_PAYLOAD':
      return action.payload;
    case 'UPDATE_COLOR_INTO_REDUCER':
      action.color = 'green';
      action.text = 'new text from reducer';
      return action;
   default:
     return state;
  }
}

export function AppWrapper({ children }) {
   const initialState = { color: 'red', text: 'new text new me' };
   const [state, dispatch] = useReducer(reducer, initialState);
   return (
     <AppContext.Provider value={{ state, dispatch }}>
      {children}
     </AppContext.Provider>
   );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM