首页 > 解决方案 > 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;

提前谢谢了!!!

标签: reactjsreduxreact-redux

解决方案


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>

推荐阅读