CodeSandbox上的代码
通过以下代码,我正在使用React Hooks
,Context
,useContext
和useReducer
。是否可以引用Context
而不必在函数中将其作为参数发送?
这是一个非常普通的示例。我的实际应用程序有一个对象,该对象具有几对key:value
对,我希望将其作为对象发送到我的API,因此我希望我的子组件能够仅更新整个key:value
对中的一对对象,这就是我的updateCurrentProgram
函数要实现的目标。
store.js (请注意,initialState
函数在updateCurrentProgram
中具有context
参数。context
被传递给子组件中的函数(例如 A.js )用于更新状态。是否可以引用context
而不用将其作为参数发送?)< / p>
import React, { useReducer, useContext } from "react";
const CTX = React.createContext();
export { CTX };
const initialState = {
currentProgram: { a: 1, b: 2, c: 3 },
updateCurrentProgram: (param, context) => {
const [{ currentProgram }, updateState] = context;
let newProgram = { ...currentProgram };
newProgram[Object.keys(param)[0]] = param[Object.keys(param)[0]];
updateState({ type: "updateCurrentProgram", payload: newProgram });
}
};
function reducer(state, action) {
switch (action.type) {
case "updateCurrentProgram":
return { ...state, currentProgram: action.payload };
default:
throw Error("reducer error");
}
}
export default function(props) {
const stateHook = useReducer(reducer, initialState);
return <CTX.Provider value={stateHook}>{props.children}</CTX.Provider>;
}
A.js (B.js和C.js相似)
我基本上希望updateCurrentProgram
函数看起来像
updateCurrentProgram({ a: nextNumber })
代替
updateCurrentProgram({ a: nextNumber }, context)
,我想知道是否有一种方法可以从我的 store.js 内部引用上下文,而不将其作为任何参数发送给我的updateCurrentProgram
函数。
import React, { useContext } from "react";
import { CTX } from "../store/store";
function A() {
const context = useContext(CTX);
const [{ currentProgram, updateCurrentProgram }, updateState] = context;
const nextNumber = currentProgram.a + 1;
return (
<div>
<p>{currentProgram.a}</p>
<button onClick={() => updateCurrentProgram({ a: nextNumber }, context)}>
Next Number
</button>
</div>
);
}
export default A;
index.js
import React from "react";
import App from "../components/App";
import Store from "../store/store";
function AppStore() {
return (
<Store>
<App />
</Store>
);
}
ReactDOM.render(<AppStore />, document.getElementById("app"));
App.js
import React from "react";
import A from "./A";
import B from "./B";
import C from "./C";
function App() {
return (
<div>
<A />
<B />
<C />
</div>
);
}
export default App;