値をカウントするための Counter という名前のクラスがあり、このクラスには、カウントに使用される inc と dec という 2 つのメソッドがあります。CounterEdit という名前の入力コンポーネントを作成し、値プロパティを Counter クラス インスタンスに接続します。カウンター クラスのカウント値が変化したときに、入力コンポーネントの更新値が必要です。これを行うには、useCounter という名前の新しいフック関数を作成します。この関数は、useReducer 自体を使用し、useReducer のディスパッチ関数を Counter クラスに渡します。カウンタークラスはそれ自体で値を増減し、ディスパッチ関数を使用してカウント値をレデューサーに送信します。レデューサーのステータスが変化すると、入力コンポーネントが更新されます。しかし、複数の入力コンポーネントを使用すると、最後の入力コンポーネントのみが更新されます。他に変更はありません。私が間違っているところについてあなたの助けを待っています。ありがとう...
class Counter {
constructor() {
this.value = 0;
}
setValue(data) {
this.dispatch({ type: "VALUE_CHANGE", payload: data });}
inc() {
this.setValue(this.value++);
}
dec() {
this.setValue(this.value--);
}
}
export { Counter };
そして今、これでクラスコンポーネントにレデューサーを使用したい
const reducer = (state, action) => {
switch (action.type) {
case "VALUE_CHANGE": {
return { count: action.payload };
}
default:
return;
}
};
const initialState = { count: 0 };
const useCounter = counterComp => {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
if (counterComp) {
counterComp.dispatch= dispatch;
}
}, [counterComp]);
return state;
};
そして、ここで入力コンポーネントがレデューサーから値を取得しています:
const CounterEdit = props => {
const state = useCounter(props.counter);
return <input type="text" value={state.count} />;
};
このアプリを実行すると、3 番目の入力値のみが変更されます。すべての入力インスタンスにカウンター値を反映させたい。
応募内容:
export default function App() {
//counter class instance
const testCounter = new Counter();
return (
<div className="App">
<div className="header">
<button onClick={() => testCounter.inc()}> Inc </button>
<button onClick={() => testCounter.dec()}> Dec </button>
</div>
<div>
<CounterEdit counter={testCounter} />
<CounterEdit counter={testCounter} />
<CounterEdit counter={testCounter} />
</div>
</div>
);
}