【问题标题】:Update useContext every second每秒更新 useContext
【发布时间】:2020-10-30 01:40:56
【问题描述】:

我有一个变量“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;

【问题讨论】:

    标签: javascript reactjs createcontext


    【解决方案1】:

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

    我看到的一个小问题

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

    【讨论】:

      猜你喜欢
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2016-09-19
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多