无法在返回之外更新上下文状态

时间:2020-02-27 22:35:58

标签: javascript reactjs react-hooks react-state-management

尝试根据元素ID“ textToColor”的输入来更新上下文状态颜色键。

setColor("yellow")工作正常 setColor("blue")不起作用,因为它正在returnInput函数中运行。 setColor(document.getElementById('textToColor').value);与上述相同,并且在setColor("yellow") works.

的返回点中也不起作用

App.js

import * as React from "react";

import { ContextOne } from "./ContextOne";

export function App() {
  // [A]
  let { state, dispatch } = React.useContext(ContextOne);

  // [B]
  React.useEffect(
    () => {
      document.body.style.backgroundColor = state.currentColor;
    },
    [state.currentColor]
  );

  // [C]
  let inc = () => dispatch({ type: "increment" });
  let dec = () => dispatch({ type: "decrement" });
  let reset = () => dispatch({ type: "reset" });
  let setColor = color => () => dispatch({ type: "set-color", payload: color });

let returnInput = () => {
    console.log('In return input');
    console.log(document.getElementById('textToColor').value);
    setColor("blue");
    //^^^ Doesn't work
    //setColor(document.getElementById('textToColor').value);
    //^^^ Doesn't work
  }

  return (
    <React.Fragment>
      <div style={{ textAlign: "center" }}>
        <p>
          Current color is: <b>{state.currentColor}</b>
        </p>
        <p>
          Current count: <b>{state.count}</b>
        </p>
      </div>
      <div style={{ paddingTop: 40 }}>
        <p>Count controls:</p>
        <button onClick={inc}>Increment!</button>
        <button onClick={dec}>Decrement!</button>
      </div>
      <div>
        <p>Color controls:</p>
        <input id="textToColor" />
        <button onClick={() => returnInput()}>Change to input color</button>
        <button onClick={setColor("yellow")}>Change to papayawhip!</button>
      </div>
      <div>
        <p>Reset changes:</p>
        <button onClick={reset}>Reset!</button>
      </div>
    </React.Fragment>
  );
  }

ContextOne.js

import * as React from "react";

let ContextOne = React.createContext();

let initialState = {
  count: 10,
  currentColor: "#bada55"
};

let reducer = (state, action) => {
  switch (action.type) {
    case "reset":
      return initialState;
    case "increment":
      return { ...state, count: state.count + 1 };
    case "decrement":
      return { ...state, count: state.count - 1 };
    case "set-color":
      return { ...state, currentColor: action.payload };
  }
};

function ContextOneProvider(props) {
  // [A]
  let [state, dispatch] = React.useReducer(reducer, initialState);
  let value = { state, dispatch };


  // [B]
  return (
    <ContextOne.Provider value={value}>{props.children}</ContextOne.Provider>
  );
}

let ContextOneConsumer = ContextOne.Consumer;

// [C]
export { ContextOne, ContextOneProvider, ContextOneConsumer };

1 个答案:

答案 0 :(得分:0)

它不在功能范围内。使用箭头功能维护范围。另外,请考虑参考Forms上的React文档,而不要使用document.getElementById