使用typescript useContext和useReducer时,始终会返回空状态,直到调度填充状态的动作为止

时间:2020-08-06 15:06:51

标签: reactjs typescript use-state use-context

如果可以的话,在组件中

import React, { createContext, useContext, useReducer } from "react";
import { PatientEntry } from "../types";

import { Action } from "./reducer";

export type State = {
  patients: { [id: string]: PatientEntry };
};

const initialState: State = {
  patients: {}
};

export const StateContext = createContext<[State, React.Dispatch<Action>]>([
  initialState,
  () => initialState
]);

type StateProviderProps = {
  reducer: React.Reducer<State, Action>;
  children: React.ReactElement;
};

export const StateProvider: React.FC<StateProviderProps> = ({
  reducer,
  children
}: StateProviderProps) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StateContext.Provider value={[state, dispatch]}>
      {children}
    </StateContext.Provider>
  );
};
export const useStateValue = () => useContext(StateContext);

那么状态就是初始状态。

在useEffect之前,期间和之后,所有状态均为空。它始终是初始状态。只要 在useEffect挂钩(将[dispatch]作为第二个参数)中调度了将新数据设置为state之后,状态为

然后我更新页面或导航到其他页面,然后返回,状态再次为初始状态

代码:

export default function App() {
    const [lastMessageId, setLastMessageId] = useState(0);
    const [messages, setMessages] = useState([]);

    const addMessage = (body, type) => {
        const newMessage = {
            id: lastMessageId + 1,
            type: type,
            body: body,
        };
        setLastMessageId(newMessage.id)
        setMessages([...messages, newMessage]);
        console.log("point 1", messages);
        return newMessage.id;
    }

    // remove a message with id
    const removeMessage = (id) => {
        const filter = messages.filter(m => m.id !== id);
        console.log("point 2", filter);
        setMessages(filter);
    }

    // add a new message and then remove it after some seconds
    const addMessageWithTimer = (body, type="is-primary", seconds=5) => {
        const id = addMessage(body, type);
        setTimeout(() => removeMessage(id), seconds*1000);
    };

    return (
        ...
    );
}

并且如果我用作useEffect患者的第二个参数 ,那么即使患者仅更改一次,页面也会重新加载无限次-在分派更改时

我只需要使用其中的所有内容来访问状态。每次我都不需要将新数据保存到其中

即使Provider.Consumer也会提供初始状态,即使上下文是通过prop传递的。

结论:更改后的状态永不保存

0 个答案:

没有答案