Redux 数据变化监听:组件如何触发重新渲染
Redux 中的数据变化是通过 dispatch 一个 action 来触发的,而组件可以监听 Redux store 中的数据变化来重新渲染。
- 使用 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);
- 在组件中使用监听的数据
在组件中使用 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。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nPG9 著作权归作者所有。请勿转载和采集!