每秒更新一次useContext

Update useContext every second

我有一个变量“second”,需要每秒更新一次。它被多个组件使用,所以我把它放在上下文中。

只有我第一次看到正确的值,从下一次迭代开始它就变成未定义的了。 有什么建议吗

输出:

state is  {second: 43, error: null}

state is  {second: undefined, error: null}

并且我在 useEffect 中使用 setInterval 每秒更新一次变量

代码

import React, { useReducer, useEffect } from "react";

export const SecContext = React.createContext();

const initialState = {
  second: new Date().getSeconds(),
  error: null,
};

const reducer = (state, action) => {
  switch (action.type) {
    case "UPDATE_SECOND":
      return {
        ...state,
        second: action.second,
      };
    default:
      throw new Error();
  }
};

export const SecContextProvider = (props) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  const updateSecond = () => {
    let second = new Date().getSeconds();
    console.log("state is ", state);
    dispatch({
      type: "UPDATE_SECOND",
      payload: second,
    });
  };

  useEffect(() => {
    const timeoutId = setInterval(() => {
      updateSecond();
    }, 1000);
    return function cleanup() {
      clearInterval(timeoutId);
    };
  }, [updateSecond]);

  return (
    <SecContext.Provider value={[state, dispatch]}>
      {props.children}
    </SecContext.Provider>
  );
};

export default SecContextProvider;

很抱歉写下这个答案,但我无法添加新评论。

我看到的一个小问题

return {
    ...state,
    second: action.second, // you refer to action.second, which is undefined, you need action.payload here
};