自定义实现一个HOC高阶组件将redux的state和dispatch注入到类组件的props
时间: 2024-05-03 16:23:33 浏览: 138
以下是一个示例代码,它将Redux的state和dispatch注入到类组件的props中:
```
import React from 'react';
import { connect } from 'react-redux';
const withRedux = (WrappedComponent) => {
class WithRedux extends React.Component {
render() {
const { dispatch, ...rest } = this.props;
return <WrappedComponent {...rest} dispatch={dispatch} />;
}
}
const mapStateToProps = (state) => ({
state: state,
});
return connect(mapStateToProps)(WithRedux);
};
export default withRedux;
```
使用方法如下:
```
import React from 'react';
import withRedux from './withRedux';
class MyComponent extends React.Component {
render() {
const { state, dispatch } = this.props;
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</div>
);
}
}
export default withRedux(MyComponent);
```
现在,您可以像这样使用MyComponent并访问Redux状态和调度操作:
```
import React from 'react';
import MyComponent from './MyComponent';
class App extends React.Component {
render() {
return (
<div>
<MyComponent />
</div>
);
}
}
export default App;
```
阅读全文