我是react和redux的新手,一直在探索它与angular的不同之处。
我试图做一个简单的登录页面,但无法实现我想要的。当我从登录表单中获得用户名和密码后,我将其提交如下:
submitHandler(e){
e.preventDefault();
var user = {
name : this.state.username,
password: this.state.password
}
this.props.authenticateUser(user);
browserHistory.push('/home');
this.setState({
username:'',
password:''
})
}在这里,authenticateUser是还原器中的一个函数(如下所示),它从已经存在的用户列表中检查状态,然后使用属性isAuthenticated检查状态:
case 'AUTHENTICATE_USER':
var users = state.userslist;
var payloadUser = action.payload;
for (let i = 0; i < users.length; i++) {
let user = users[i]
if (user.name === payloadUser.name) {
return {...state, isAuthenticated: true };
}
};
return {...state, isAuthenticated: false };现在,我只需要等待这个调用完成,并检查这个值是true还是false,然后使用angular-router导航到主页。
但是我如何在react中实现同样的目标呢?我在我的示例应用程序中使用react-router。
我试着在调用isAuthenticated的submitHandler函数下面检查this.props.authenticateUser(user),但问题是,this.props.isAuthenticateUser没有更新并返回false,我在还原器中将其设置为initialState。
请告诉我如何在isAuthenticated函数调用之后检查authenticateUser,这样我就可以继续我的主页路由。我是否必须使用promise并等待redux更新状态,然后再检查它??(我知道,反应是单向的,不是这样的。)
此外,如果身份验证失败,如何在登录表单下面显示错误面板。我认为为错误面板使用一个组件,该组件接受isAuthenticated作为输入,并检查是否为false,以便显示(即。( ngShow似角。)但我担心这也不起作用,因为我的状态不会及时更新。
我知道在状态发生任何变化时都会调用render函数。但我就是不能把头绕得很清楚。
编辑:为了简洁起见,我没有提供上面提到的动作创建者和完整还原器,而是只显示了用于身份验证用户的开关用例操作。我的应用程序遵循最初的redux体系结构,包括动作、还原器、容器、组件等等。
编辑: Github链接这里
发布于 2017-02-05 21:16:30
我将试图简要解释Redux应用程序中数据流是如何工作的:
type: AUTHENTICATE_USERaction.type (上面的第二个代码片段)更新redux状态。mapStateToProps方法,它作为道具将值从Redux状态传递到组件中。因此,当状态发生变化时,道具将被更新,组件将重新呈现。要使用mapStateToProps,需要从redux库实现连接。(https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options)为了实现你想要的,我建议:
componentWillReceiveProps方法中,检查props.isAuthenticated并在用户通过身份验证时使用context.router.push()导航。props.isAuthenticated方法中进行基于render的检查,以显示错误消息。有几个可能有用的链接:
发布于 2020-06-02 14:30:37
我更喜欢这样的代码:
const mapStateToProps = (state) => {
return {
isAuthenticated: state.isAuthenticated
}
}
class Dashboard extends PureComponent {
render() {
const { isAuthenticated } = this.props
return (
<div>
{ isAuthenticated ? (
<div>
<p>Hello</p>
</div>
) : (
Login()
)}
</div>
)
}
}来源:https://stackoverflow.com/a/56899814/3850405
除了@Nupur的答案之外。componentWillReceiveProps()被认为不安全,现在的方法名是:UNSAFE_componentWillReceiveProps()
使用componentDidUpdate()代替,如果您想要这种方法,这个方法是不被调用的初始渲染。
componentDidUpdate(prevProps) {
if (this.props.isAuthenticated ) {
//perform code here
}
}https://reactjs.org/docs/react-component.html#componentdidupdate
https://stackoverflow.com/questions/42055234
复制相似问题