随笔

React State Manage API

Context

需要多层传递属性时,可以使用它,避免了 props 一层层传递的问题。但是可能有问题的是值发生改变时,所有消费组件都会重新渲染。

const ThemeContext = React.createContext('light');
...
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
...
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

<ThemeContext.Consumer>
  {value => /* 基于 context 值进行渲染*/}
</ThemeContext.Consumer>

Hook

想来也只能写写API了

useEffect

每次渲染都会执行的一个回调函数

useEffect(() => {
  return () => {  };
});

useState

展开两个参数,第一个是数据,第二个是可以更新这个数据的函数,这个函数和 setState 不同的是全量更新的

const [count, setCount] = useState(initialCount);

useReducer

这里在后面多了一个函数,这个函数就相当于把 useState 更新的实现交给开发者了

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

比如,这里根据传入的参数处理不同的逻辑

dispatch({type: 'increment'})
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

先更新到这,之后有了更深入使用的理解后再更新。mobx已经出了一个基于 hook 的版本


写了一个 todo 小例子, 使用 hook + context
https://github.com/lilonghe/experiment/tree/master/react-hook-intro

本文链接:https://note.lilonghe.net//post/react-state-manage-api.html

-- EOF --