react-redux中的dispatch()如何使用
时间: 2024-03-14 12:45:00 浏览: 18
在React-Redux中使用`dispatch()`函数,需要在组件中通过`connect()`函数将组件与Redux store进行连接。然后,就可以在组件中通过`props`访问`dispatch()`函数了。
下面是一个简单的例子,演示了如何在组件中使用`dispatch()`函数:
```jsx
import React from 'react';
import { connect } from 'react-redux';
class MyComponent extends React.Component {
handleClick = () => {
this.props.dispatch({ type: 'INCREMENT' });
};
render() {
return (
<div>
<p>Count: {this.props.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
function mapStateToProps(state) {
return {
count: state.count
};
}
export default connect(mapStateToProps)(MyComponent);
```
在这个例子中,我们定义了一个名为`MyComponent`的组件,并将它与Redux store进行连接。通过`connect()`函数,我们将`mapStateToProps`函数传递给`connect()`函数,从而将Redux store中的状态映射为组件的props。这里,我们将`count`状态映射为`this.props.count`。
在组件中,我们定义了一个`handleClick()`函数,用于在按钮被点击时调用`dispatch()`函数。在`handleClick()`函数中,我们使用`this.props.dispatch()`来派发一个`INCREMENT` action,从而更新Redux store中的状态。
最后,我们通过`export default connect(mapStateToProps)(MyComponent)`将`MyComponent`组件与Redux store进行连接并导出。