Context+Reduce配合详解

111 阅读2分钟

Context 向组件深层传递数据

  1. 通常来说,你会通过props将信息从父组件传递到子组件。但是,如果你必须通过许多中间组件,向下传递props,或是在你应用中的许多组件需要相同的信息,传递props会变的十分冗长
  2. Context允许父组件向其下层无论多深的任何组件提供信息,而无需通过props显式传递 在下例中用App父组件嵌套一个Second组件并在其中再嵌套Third组件。
import { createContext, useContext } from 'react'
const Strange = createContext(0)
function Third() {
  const count = useContext(Strange)
  return (
    <div>
      hello Third
      {count}
    </div>
  )
}
function Second() {
  return <div>hello second <Third/>
  </div>
}
function App() {
  return (
    <Strange.Provider value={123}>
      <Second />
    </Strange.Provider>
  )
}
export default App

其中用到两个钩子函数

  1. createContext父组件中传 const Strange = createContext(0)用此方法定义一个变量后,<Strange.Provider value={123}>用点语法的方式提供数据,类似组件的方式,并在里面包含子组件。
  2. useContext子组件接收 然后跳过Second组件直接在Third组件中用useContext(Strange)接收。 在App中添加点击事件等来改变count的状态,子组件Third也能跟着改变。

Reducer 配合Context实现共享状态管理

Reducer 可以整合组件的状态更新逻辑。Context可以将信息深入传递给其他组件。你可以组合 使用它们来共同管理一个复杂页面的状态 更复杂的状态管理,可以采用第三方库:Redux,Mobx,Zustand等。 在下面例子中向父子组件通讯方法 为实现对数组增删改的操作,并将增删改的点击按钮放在不同组件中,来回调用。 <ListProvider> <ListAdd /> <ListChange /> </ListProvider>将提供数组和增删改方法放在,添加按钮在 ,修改,删除按钮在 。在ListProvider中用reducer封装方法,并export const List = createContext() export const DisList = createContext()将方法和数组分别传递返回 <List.Provider value={list}> <DisList.Provider value={disPatch}>{children}</DisList.Provider> </List.Provider><ListChange />中调用

         const list = useContext(List)
  const disPatch = useContext(DisList)

  return (
    <ul>
      {list.map((item) => {
        return (
          <li key={item.id}>
            {item.text}
            <button onClick={() => disPatch({ type: 'delet', id: item.id })}>
              删除
            </button>
            <button onClick={() => disPatch({ type: 'edit', id: item.id })}>
              修改
            </button>
          </li>
        )
      })}
    </ul>
  )