React Tutorial (updating)
生活随笔
收集整理的這篇文章主要介紹了
React Tutorial (updating)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Document
當我們需要同時獲取多個子組件數據,或者兩個組件需要互相通訊的時候,可以把狀態存入父組件當中。然后父組件再把狀態傳遞到子組件當中。
Hook
It is like the useState, it is used to manage the state of the hook.
useReducer is the primitive hook compared to useState.
a. reducer
b. useReducer
example1
example2:
import React, {useReducer} from 'react' //make state as an object const initalState = {firstCounter: 0 } const reducer = (state, action) => {switch(action.type) {case 'increment':return {firstCounter: state.firstCounter + action.value}case 'decrement':return {firstCounter: state.firstCounter - action.value}case 'reset':return initialStatedefault:return state } }function Counter (){const [count, dispatch] = useReducer(reducer, initialState)return (<div><Button onClick = {() => dispatch({type:'increment', value:1})}>Increment</Button><Button onClick = {() => dispatch({type:'increment', value:5})}>Increment by 5</Button><Button onClick = {() => dispatch({type:'decrement',value:1})}>Decrement</Button><Button onClick = {() => dispatch({type:'decrement',value:5})}>Decrement by 5</Button><Button onClick = {() => dispatch({type:'reset'})}>Reset</Button></div>) } export default Counterc. useReducer with useContext(share state between components)
在不同的組件里拿到同樣的一個值
在Component里面:
import {CountContext} from "../APP" function ComponentA() {const countContext = useContext(CountContext)<div><Button onClick = {() => countContext.countDispatch('increment')}>Increment</Button><Button onClick = {() => countContext.countDispatch('decrement')}>Decrement</Button><Button onClick = {() => countContext.countDispatch('reset')}>Reset</Button></div> } export defalut ComponentAd.
總結
以上是生活随笔為你收集整理的React Tutorial (updating)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网页搜题插件使用
- 下一篇: 便携式明渠流量计(比对装置)——适用于四