你可能不需要用Redux

183 阅读1分钟

"当你不知道自己该不该用redux的时候,你就不需要用redux"。


鉴于前端早下班的大环境,简单页面只需要复制粘贴ant design、iview、element...的代码改改即可完成页面、交互、取值、赋值。so...


组件通信方式也应该以早下班为目的,手段就是react context api。


基本用法(基于create-react-app的项目骨架):

  1. 创建一个context
// App.js
import React, { useState } from "react"

export const { Provider, Consumer } = React.createContext({  inputValue: ""})
  1. 绑定Provider到App组件上

(就是把要共享的状态变量放在App组件状态中管理,因为它是其他组件的共同父亲)

// App.js
export default () => {
  let [inputValue, setInputValue] = useState('')

  const onUserInput = newVal => {
    setInputValue(newVal)
  }

  return (
    <Provider
      value={{val: inputValue, onUserInput: onUserInput }}
    >
      <div className="app">
        <A />
      </div>

      <Alone />
    </Provider>
  )
}
  1. 更新共享的状态变量
// App.js
const B = () => (
  <div className="child">
    <span className="title"> B</span>
    <Consumer>
      {({ val, onUserInput }) => (
        <input
          type="text"
          style={{height: '20px'}}
          value={ val }
          onChange={e => onUserInput(e.target.value)}
        />
      )}
    </Consumer>
  </div>
)
  1. 获取共享的状态变量
// App.js
const C = () => (
  <div className="child">
    <span className="title"> C </span>
    <Consumer>{({ val }) => <p>{ val }</p>}</Consumer>
  </div>
)

// or

// Alone.js
import React from 'react';
import { Consumer } from "../App";

export default () => (
  <div style={{textAlign: 'center', fontSize: '28px'}}>
    <p>Alone</p>
    <Consumer>{({ val }) => <p>{ val }</p>}</Consumer>
  </div>
)

  1. 6点了,下班了,放上演示效果和示例源代码