我没用过useReducer。 我有一个带有useReducer的组件。它必须增加和减少按钮。当我单击状态更新时,我们可以看到更改..但仅对于该组件,使用相同状态的第二个组件也不会更新..直到单击inc或dec按钮
import React, { Component,useReducer } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
export const appstate = {
foo: 99
};
export function freducer(state, action) {
switch (action.type) {
case 'increment':
appstate.foo+=1;
return {...appstate};
case 'decrement':
appstate.foo-=1;
return {...appstate};
default:
throw new Error();
}
}
export function Dap(prop) {
const [state, dispatch] = useReducer(freducer, appstate)
console.log(state);
return (
<>
foo: {state.foo}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
render(<>
<Dap />
<hr/>
<Dap />
</>, document.getElementById('root'));
代码和工作地点在https://stackblitz.com/edit/react-wrql5k
我已经走了很多堆栈溢出的链接..无法理解。