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



尝试根据元素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 };

它不在函数的范围内。使用箭头函数来维护范围。此外,请考虑参考表单上的React文档,而不是使用document.getElementById

相关内容

  • 没有找到相关文章

最新更新