reactjs - React-redux:未触发 mapStateToProps()
问题描述
我正在尝试编写代码以在 react 和 react-redux 中执行以下操作:
1. 用户使用电子邮件和密码使用登录表单登录。
2.信息正确后,从数据库中查询用户信息(用户名、头像等),保存到Javascript对象中。
3.触发将对象发送到reducer的动作。
4.Reducer 将对象放入 store。
5.商店更新后,返回用户名并将其呈现到登录页面。
我编写了下面的代码并使用console.log,我看到#3之前的所有步骤都可以正常工作。但是,用户名不会返回到原始页面。我使用了 mapStateToProps(),当我登录控制台时,它根本没有被调用。也许是因为 store 实际上没有被更新,或者是因为 mapStateToProps() 实现有问题。有人可以查看下面的代码并帮助我吗?
以下是代码:
登录.js
import React from 'react';
import './App.css';
import * as firebase from 'firebase';
import {connect} from 'react-redux';
import {actionCreators} from './Store';
let userinfo={}; //To save the info queried by the 'signin' function
const signin = () => {
/*
Code for querying data from Database. Works fine.
*/
actionCreators.login(userinfo); // After the query is done, trigger the action to update the store. This one works fine too
}
function Signin(props) {
return (
<div>
/*
Component description for signin form
*/
<button className="login_button" id ="lib" onClick={signin}>Sign in</button>
<div>
Hello, {props.username}!
</div>
</div>
)
}
function mapDispatchToProps(dispatch,userinfo) {
return {
login: () => dispatch(actionCreators.login(userinfo))
}
}
function mapStateToProps(state) {
return {
username: state.username
};
}
export default connect(mapStateToProps,mapDispatchToProps)(Signin);
Store.js // 我知道这段代码最终应该被拆分。只是为了检查逻辑是否有效。
import {createStore} from 'redux';
const loggedIn="loggedIn";
const login=(obj)=>{
return {
type:loggedIn,
payload:obj
}
}
const reducer=(state={},action) => {
switch(action.type){
case loggedIn:
return Object.assign({},state, action.payload);
default:
return state;
}
};
const store=createStore(reducer);
export const actionCreators = {
login,
};
export default store;
提前谢谢了!!!
解决方案
actionCreators.login(userinfo); // After the query is done, trigger the action to update the store. This one works fine too
这不会分派动作。它只是创建动作,然后什么都不做。为了让你的 reducer 被调用,你需要调度这个动作。
您已经在使用 mapDispatchToProps 创建登录道具,因此您需要使用它。你signin
在组件之外创建了一个额外的函数对我来说似乎很奇怪,但是由于省略了该代码,我无法就替代方法给你一个建议。因此,如果您需要保留该signin
功能,则需要进行两次调用:一个 to signin
,一个 to props.login
:
<button className="login_button" id ="lib" onClick={() => {
signin();
props.login(userinfo);
}}>Sign in</button>
推荐阅读
- python - Streamlit 和会话状态(用于 Python 和 Pandas)
- ssrs-tablix - 字段 X 的值表达式包含错误:[BC30277] 类型字符“&”与声明的数据类型“对象”不匹配。?
- rest - 使用 Delighted API 的 ADF 分页问题 - 请求正文值无法识别
- c - Codeforces 的问题 151A 我用 C 语言编写了这个程序,我认为它有一些问题。请帮帮我
- assembly - System V AMD64 ABI 是 %gs 调用者还是被调用者保存?
- salesforce - 更改闪电输入中的图标位置以用于 LWC 中的搜索类型
- odata - 逻辑应用表存储获取实体操作返回无/异常结果
- node.js - 在 IIS 上提供 Angular 客户端和 Express Sever,而不破坏 URL
- docker - 为什么我的开发容器中没有 VS Code 功能?
- php - WordPress after_password_reset 未触发