Redux 中的数据变化是通过 dispatch 一个 action 来触发的,而组件可以监听 Redux store 中的数据变化来重新渲染。

  1. 使用 connect 函数连接组件和 Redux store

通过 connect 函数,把组件和 Redux store 连接起来,这样组件就可以监听 store 中数据的变化了。在 connect 函数中,可以通过 mapStateToProps 函数把需要监听的数据映射到组件的 props 中。

import { connect } from 'react-redux';

const mapStateToProps = (state) => {
  return {
    data: state.data,
  };
}

export default connect(mapStateToProps)(MyComponent);
  1. 在组件中使用监听的数据

在组件中使用 Redux store 中的数据时,直接使用 props 中的数据即可。当 Redux store 中的数据发生变化时,props 也会相应地更新。

import React from 'react';

const MyComponent = (props) => {
  const { data } = props;

  return (
    <div>{data}</div>
  );
}

export default MyComponent;

当 Redux store 中的数据发生变化时,组件会自动重新渲染,从而更新 UI。

Redux 数据变化监听:组件如何触发重新渲染