这是一个包含以下示例代码的 CodeSandbox,linter 突出显示了一些问题:https ://codesandbox.io/s/react-repl-bw2h1
下面是我正在尝试做的一个基本示例。在容器组件中,我有一个AppContext
为子组件提供状态的上下文,<ChildConsumer />
并且<ChildDispatcher />
.
<ChildConsumer />
组件使用 接收此状态,useContext
这似乎按预期工作。
在里面<ChildDispatcher />
,我试图在单击按钮时调度一个动作。为此,我创建了一个reducer
处理动作的减速器。我还在这里设置了 useReducer 来接收reducer
初始store
状态。
当我单击按钮时,什么也没有发生。我期望发生的是,dispatch
既接收state
拉出useReducer
的对象,也接收action
对象,并将它们传递给减速器。reducer 应该看到BUTTON_CLICKED
收到了 type 的 action,并且应该返回一个包含旧状态的新状态以及一个附加'goodbye'
项。然后,子组件<ChildConsumer />
应该使用这个新状态重新渲染。
import React, { createContext, useContext, useReducer } from "react";
import ReactDOM from "react-dom";
const store = [""];
const AppContext = createContext(store);
const ChildDispatcher = () => {
const reducer = (state, action) => {
switch (action.type) {
case "BUTTON_CLICKED":
return [...state, "goodbye"];
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, store);
const handleClick = () =>
dispatch(state, {
type: "BUTTON_CLICKED"
});
return <button onClick={handleClick}>press me</button>;
};
const ChildConsumer = () => {
const [consumer] = useContext(AppContext);
return <div>{consumer}</div>;
};
const App = () => {
return (
<div>
<h1>Using Context and useReducer</h1>
<AppContext.Provider value={["hello"]}>
<ChildConsumer />
<ChildDispatcher />
</AppContext.Provider>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);