React组件之间通信

45 阅读1分钟

props和callback

父传子

function Father(){
  const [count, setCount] = useState();
  return (<Child count={count}/>)
}
function Child(props){
  return (<div>{props.count}</div>)
}

子传父

function Father(){
  function getCount(count){
    console.log(count)
  }
  return (<Child getCount={getCount}/>)
}
function Child(props){
   const [count, setCount] = useState();
  return (<div onClick={()=>props.getCount(count)}>'getCount'</div>)
}

兄弟

子1传父、父传子2

Context

特定场景使用:路由、主题、全局的共享信息

ref

状态管理库

redux

  • 使用单一store作为数据源
  • store只读,唯一改变store是action
  • 使用纯函数来修改,接受之前的store和action,返回新的store

缺点

  • 学习曲线陡峭,副作用交给中间件处理,社区中间件很多,导致得学中间件
  • 大量的模版代码,action、store,跟逻辑无关
  • 性能问题,state更新会影响所有的组件,action会调用所有的reducer

mobx

mobx三个概念

  • state
  • actions
  • derivations(派生) derivations分为Computed Values(计算值)和Reactions(副作用)

zustand

hooks