【问题标题】:React - ContextAPI not setting correct stateReact - ContextAPI 没有设置正确的状态
【发布时间】:2020-12-04 23:58:18
【问题描述】:

我想知道我在这里做错了什么。调度方法正在调度正确的值,但状态对象显示错误的值。

{ name: "name", room: "room" } 是我单独发送的。但是状态显示 { name: "room": room: "" }

谷歌浏览器日志

注意:如果需要,请从 github 存储库中签出代码 here

减速机:

export const initialState = {
    name: '',
    room: ''
}

export const reducer = (state, action) => {
    console.log("Calling action", action);
    switch (action.type) {
        case types.SET_NAME:
            return { ...state, name: action.name }
        case types.SET_ROOM:
            return { ...state, name: action.room }
        default:
            return state;
    }
}

_app 组件:


import DataProvider from "../context/DataProvider";
import { initialState } from '../reducers/index';
import { reducer } from '../reducers';


const AppComponent = ({ Component, pageProps }) => {
    return (
        <DataProvider intialState={initialState} reducer={reducer}>
            <Component {...pageProps} />
        </DataProvider>
    )
}

AppComponent.getInitialProps = async (appContext) => {
    let pageProps = {};
    if (appContext.Component.getInitialProps) {
        pageProps = await appContext.Component.getInitialProps(appContext.ctx);
    }
    return { pageProps }
}

export default AppComponent;

组件

const Join = () => {
    const [name, setName] = input('');
    const [room, setRoom] = input('');
    const [state, dispatch] = useContext(DataContext);

    const submit = (e) => {
        if (name === '' || room === '') {
            e.preventDefault();
            return;
        }
        dispatch({
            type: types.SET_NAME,
            name
        });
        dispatch({
            type: types.SET_ROOM,
            room
        });
    }

    return (
        <div>
            <h1>Join</h1>

            <input onChange={(e) => setName(e)} placeholder="name" />
            <input onChange={(e) => setRoom(e)} placeholder="room" />
            <Link href="/chat">
                <button type="submit" onClick={(e) => submit(e)}>Submit</button>
            </Link>

        </div>
    )
}

聊天组件(我正在消费的状态):

const Chat = () => {
    // const backendEndpoint = 'http://localhost:5000';
    const [state, dispatch] = useContext(DataContext);
    console.log('STATE', state)
    return <h1>Chat</h1>
}

Chat.getInitialProps = async (ctx) => {
    return {}
}

export default Chat;

【问题讨论】:

    标签: reactjs react-redux react-router react-context


    【解决方案1】:

    我认为问题出在你的减速器上

    case types.SET_ROOM:
    return { ...state, name: action.room }
    

    在这里您可以更改rooms 操作中的name

    也许你需要像这样更新 return { ...state, room: action.room }

    【讨论】:

      【解决方案2】:

      实际上你在 Reducer.js 中犯了一个错误

      export const reducer = (state, action) => {
          console.log("Calling action", action);
          switch (action.type) {
              case types.SET_NAME:
                  // equals state.name = action.name
                  //  state = { name: 'name', room: '' }
                  return { ...state, name: action.name }
              case types.SET_ROOM:
                  // equal state.name = action.room
                  //  state = { name: 'room', room: '' }
                  return { ...state, name: action.room }
              default:
                  return state;
          }
      }
      
      // u can change your code style to reduce mistakes
      export const reducer = (state, action) => {
          const {name, room} = action
          switch (action.type) {
              case types.SET_NAME:
                  return { ...state, name }
              case types.SET_ROOM:
                  return { ...state, room }
              default:
                  return state;
          }
      }
      

      【讨论】:

      • 哦该死的。感谢这个漂亮的方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2019-07-31
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多