【发布时间】:2020-03-07 17:20:30
【问题描述】:
这是一个 CodeSandbox,其中包含以下示例代码,linter 突出显示了一些问题:https://codesandbox.io/s/react-repl-bw2h1
下面是我正在尝试做的一个基本示例。在容器组件中,我有一个上下文AppContext,它为子组件<ChildConsumer /> 和<ChildDispatcher /> 提供状态。
<ChildConsumer /> 组件正在使用useContext 接收此状态,这似乎按预期工作。
在<ChildDispatcher /> 中,我试图在单击按钮时调度一个动作。为此,我创建了一个处理动作的减速器reducer。我还在此处设置了 useReducer,它接收 reducer 和初始 store 状态。
当我点击按钮时,什么也没有发生。我期望发生的是dispatch 接收从useReducer 拉出的state 以及action 对象,并将它们传递给reducer。 reducer 应该看到BUTTON_CLICKED 类型的动作被接收,并且应该返回一个包含旧状态的新状态以及一个额外的'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);
【问题讨论】:
-
你将如何真正重构它以将每个孩子放在自己的文件中?
标签: javascript reactjs react-redux react-hooks use-reducer