问题
My code
class LoginPage extends Component {
render() {
return (
<div>
<TextInput/>
<br/>
<TextInput/>
<br/>
<Button onClick={() => {
const dispatcher = useDispatch();
dispatcher(singIn())
}}>SING IN</Button>
</div>
);
}
}
I guess that I am using a hooks in a class component, but what can I use instead of useDispacth to my LoginPage?
回答1:
For class components, you need to use connect method from react-redux. Use connect method and pass mapDispatchToProps function as shown below.
import { connect } from 'react-redux';
class LoginPage extends Component {
render() {
return (
<div>
<TextInput/>
<br/>
<TextInput/>
<br/>
<Button onClick={() => {
this.props.singIn()
}}>SING IN</Button>
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
signIn: () => dispatch(signIn())
}
};
export default connect(null, mapDispatchToProps)(LoginPage)
Read thru the doc for more info. https://react-redux.js.org/api/connect
来源:https://stackoverflow.com/questions/61093603/how-to-use-a-dispatch-react-redux-into-class-component