React native 如何在分派后更新状态
我是react native和redux的新手,我想知道如何在发送后更新状态 按照我的代码: /LoginForm.jsReact native 如何在分派后更新状态,react-native,redux,react-redux,React Native,Redux,React Redux,我是react native和redux的新手,我想知道如何在发送后更新状态 按照我的代码: /LoginForm.js function mapStateToProps(state) { return { user: state.userReducer }; } function mapDispatchToProps(dispatch) { return { login: (username, password) => { dispatch(logi
function mapStateToProps(state) { return { user: state.userReducer }; }
function mapDispatchToProps(dispatch) {
return {
login: (username, password) => {
dispatch(login(username, password)); // update state loggedIn
}
}
}
const LoginForm = connect(mapStateToProps, mapDispatchToProps)(Login);
export default LoginForm;
loginOnPress() {
const { username, password } = this.state;
this.props.login(username, password);
console.log(this.props.user.loggedIn)
}
/Login.js
——这里有一个按钮,它调用这个方法loginOnPress()
根据上面的代码,我首先调用方法“this.props.login(用户名、密码);”调用分派并更改状态“loggedIn”
之后,我尝试更新状态,但没有成功:
console.log(this.props.user.loggedIn)
注意:当我第二次单击此按钮时,状态将更新呼叫调度将立即更新状态,但您的组件将稍后更新,因此您可以使用
组件将接收道具
对道具的更改作出反应,您可以查看关于状态更改如何在React中工作的更好解释函数this.props.login(用户名、密码)
在redux状态下发送登录操作
启动store.getState()
确实会在更新后立即获得redux状态,但通常情况下,您并不需要这样做,因为包装组件的reduxconnect
函数
reduxconnect
功能使用新道具更新您的组件,因此您通常会在以下功能之一中“捕获”这些更改:
您应该在
组件WillReceiveProps
生命周期挂钩中检查道具更改,因为当您在尝试设置道具后在下一行检查道具时,它们的更改可能尚未传播回您的组件。这正是我需要的!谢谢你的帮助这正是我需要的,谢谢你提供的所有细节
class Greeting extends React.Component {
...
loginOnPress () {
const { username, password } = this.state;
this.props.login(username, password);
}
// before the new props are applied
componentWillReceiveProps (nextProps) {
console.log(nextProps.user.loggedIn)
}
// just before the update
componentWillUpdate (nextProps, nextState) {
console.log(nextProps.user.loggedIn)
}
// immediately after the update
componentDidUpdate (prevProps, prevState) {
console.log(this.props.user.loggedIn)
}
render() {
...
}
}