反応フック- usestateとusereducerカンニングペーパー- Redux
12753 ワード
私は理解するのに苦労していた
学び
あなたが知っているならば
比較する
たとえば、カウンタを減らすためにもう一つのボタンを加えたいです.
使用するコードはこちら
次に、減速器機能を書きます
例えば、私は呼ぶ
useReducer
私はreduxの背景を持っていないので.それで、私はそれを自分自身に説明するためにこの記事を書きました.学び
useState
ファーストあなたが知っているならば
useState
次に、このセクションをスキップすることができますuseReducer
to useState
.useState
例reactjs.org )
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
const [count, setCount] = useState(0);
useState(0)
: 初期状態(この場合は0)を渡し、2要素の配列を返します.count
and setCount
. count
: 新国家setCount
: 状態値を変更する関数.如しthis.setState()
クラスベースのコンポーネントです.比較する
useReducer
useReducer
複雑に使われるstate
状況たとえば、カウンタを減らすためにもう一つのボタンを加えたいです.
使用するコードはこちら
useState
useState
例reactjs.org ) const [count, setCount] = useState(0);
return (
<div>
{count}
<button onClick={() => setCount(count + 1)}>
+
</button>
<button onClick={() => setCount(count - 1)}>
-
</button>
</div>
);
}
我々は移動する予定ですcount+1
and count -1
にFUNCTION
使用によってuseReducer
const [count, setCount] = useReducer(FUNCTION, {count: 0})
インuseReducer
, コールcount
ASstate
, setCount
ASdispatch
, and FUNCTION
is reducer
このように見えます.const [state, dispatch] = useReducer(reducer, {count: 0})
MDN かなりよく説明しますArray.prototype.reduce()
そうです.それはあなたが何であるかuseReducer
.次に、減速器機能を書きます
reducer function
パラメータ2パスfunction reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
state
: 現状action
: 状態を変更したい場合はdispatch関数を呼び出します.この場合、最初の要素はtype
, 参照action.type
.例えば、私は呼ぶ
dispatch({type: 'increment'})
, then count
は+ 1になります.<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
完全なコードfunction reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, {count: 0});
return (
{state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
それはあなたを助ける希望!❤️Reference
この問題について(反応フック- usestateとusereducerカンニングペーパー- Redux), 我々は、より多くの情報をここで見つけました https://dev.to/mingyena/react-hooks-usestate-and-usereducer-cheat-sheet-for-developers-who-don-t-know-redux-44fnテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol