这是一个具有以下示例代码的CodeSandbox,而linter突出显示了一些问题:https ://codesandbox.io/s/react-repl-bw2h1
以下是我要执行的操作的基本示例。在一个容器组件,我有一个背景AppContext
是,以子组件提供状态,<ChildConsumer />
和<ChildDispatcher />
。
该<ChildConsumer />
组件使用接收这种状态下useContext
,这似乎是按预期工作。
在内部<ChildDispatcher />
,我试图在单击按钮时调度一个动作。为此,我创建了一个reducer
处理动作的reducer 。我还在这里设置了useReducerreducer
并接受了初始store
状态。
当我单击按钮时,什么也没有发生。我期望发生的事情是,dispatch
接收到的既是对象的state
提取内容,又useReducer
是action
对象的内容,然后将其传递给减速器。减速器应看到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);
我在您的代码中做了一个小修改。
您必须像下面那样通过调度。调度需要一个类型为object的参数。
const handleClick = () => dispatch({ type: "BUTTON_CLICKED" });
然后可以像这样访问此状态。
const ChildDispatcher = () => {
const reducer = (state, action) => {
switch (action.type) {
case "BUTTON_CLICKED":
//action.state // like this
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>;
};
默认情况下,react会将状态传递给调度程序。但是,如果要传递一些数据,则可以将其添加到对象中,然后将该对象传递给分派对象。
const handleClick = () => dispatch({ type: "BUTTON_CLICKED", state: state });
CodeSandBox:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句