useReducer 和 useContext

useReducer 和 useContext

useReducer 是一个 React Hook,它允许你向组件添加一个化简器。

useContext 是一个 React Hook,它允许你从组件中读取和订阅上下文。

useContext使用方法

1、在全局createContext

const globalContext = createContext()

2、在需要传递参数的组件外面套一层Context.Provider,并把要传递的参数写在value中

<globalContext.Provider value="dark">
  <Form />
</globalContext.Provider>

3、在需要接受参数的组件中使用useContext

function Form() {
  return (
    <Panel title="Welcome">
      <Button>Sign up</Button>
      <Button>Log in</Button>
    </Panel>
  );
}

function Panel({ title, children }) {
  const theme = useContext(ThemeContext);
  const className = 'panel-' + theme;
  return (
    <section className={className}>
      <h1>{title}</h1>
      {children}
    </section>
  )
}

Redux原理

这是图片

ui操作 -> dispatch方法 -> 进入store,调用对应reducer改变state

使用方法

1、在外部定义reducer方法,以处理dispatch传递的action

const reducer = (prevState,action) => {
  let newState = {...prevState}
  newstate.list[action.type-1] = action.value;
  return newstate
}

2、在函数内部定义state和dispatch方法

const [state, dispatch] = useReducer(reducer, initialState)

3、在需要使用或改变该状态的地方使用useContext,将state和dispatch方法传入

<globalContext.Provider value={{
	       state,
	       dispatch
	 }}>

    <View id='filt' >
        <Gameselect text = '场地' ><Placechild type='1' ItemText = {placeList} func={Info}></Placechild></Gameselect>
        <Gameselect text = '时间'  ><Placechild type='2' ItemText = {timeList} func={Info}></Placechild></Gameselect>
        <Gameselect text = '人数' ><Placechild  type = '3' ItemText = {crowdList} func={Info}></Placechild></Gameselect>                
    </View>          
 </globalContext.Provider>

4、在组件中调用dispatch方法,改变state

export function Placechild(props) {
  const {dispatch} = useContext(globalContext)
  const {state} = useContext(globalContext)
  // console.log(state);
  const{
    type,
    ItemText,
    func
  } = props
  
  return (
    <View>

      {ItemText.map((text,index)=>{
        return (
          <View onTap={async ()=>{
            await dispatch({
              type:`${type}`,
              value:`${index}`
            })
            func(type-1,index)
            }}>
            <GameSelctItem type = {type} text = {text}  style = {state.list[props.type-1]} index ={index}/>
          </View>
        )
      })}
      
    </View>
  )
}

useReducer 和 useContext
http://baidu.com/2023/03/03/useReducer/
作者
KB
发布于
2023年3月3日
许可协议