redux6 - 實現 react-redux 前置技能react 高階組件的使用

react-redux使用演示

代碼太多,就放codesandbox.io 了,可以看到,在組件中連接倉庫和組件的一個重要方法, connect() ,該方法的返回值就是個高階組件


什麼是高階組件

  • 高階組件: 同高階函數,參數可以是組件, 或者返回一個組件,
  • 使用場景: 一般用於公共部分的抽離,對一個組件進行包裝,讓它產生一些新的功能,或者返回一個新的UI組件

演示效果:

class App extends Component {
  render() {
    return (
      <>
        <h1>我是被包裝後的組件</h1>
        <span>{this.props.msg}</span>
        <h2 style={{ color: this.props.color }}>{this.props.info}</h2>
      </>
    );
  }
}
function connect(WarpComponent) {
  return class extends Component {
    state = {
      msg: '高階組件',
      info: '二柱子,薩斯給',
    };
    componentDidMount() {
      this.setState({
        color: '#f65',
      });
    }
    render() {
      return (
        <div>
          <p>hello,我是高階組件</p>
          <WarpComponent {...this.state} />
        </div>
      );
    }
  };
}
App = connect(App);
ReactDOM.render(<App />, document.getElementById('root'));

再比如說,前邊的redux使用時,在每個CounACoutB組件都寫了以下代碼,那這個代碼就可以拆出來了

  componentDidMount() {
    this.unsubscribe = store.subscribe(() =>
      this.setState({ num: store.getState().count1.num }),
    );
  }
  componentWillUnmount() {
    this.unsubscribe();
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章