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)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 网页搜题插件使用
- 下一篇: 便携式明渠流量计(比对装置)——适用于四