React redux - 使用新值更新对象状态

时间:2017-10-09 11:23:59

标签: reactjs redux react-redux

我第一次使用Redux,而且我没有成功更新状态。以下是工作流程:用户登录应用程序(/login),令牌存储在sessionStorage中,我发送用户信息以访问/dashboard/:id页面中的userData。

现在,当我在仪表板组件上安装console.log道具时,结果如下:

userData : {}

因此对象userData仍为空。 这是代码:

LoginForm:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { bindActionCreators } from 'redux'; 
import { connect } from 'react-redux';
import  * as authActions from '../../actions/authActions';


class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            errors: {},
            isLoading: false,
        };
    }

    onChange(e) {
        this.setState({
            [e.target.name]: e.target.value
        })
    }

    onSubmit(e) {
        e.preventDefault();
        this.setState({ errors: {}, isLoading: true });
        this.props.actions.logInUser( { data: { user: { email: this.state.email, password: this.state.password }}})
    }

    render() {
        return(
            <div>
                <form onSubmit={this.onSubmit.bind(this)}>
                    <div className="field">
                        <label className="label"> Email </label>
                        <div className="control">
                            <input type="email"
                                   name="email"
                                   value={this.state.email}
                                   onChange={this.onChange.bind(this)}
                                   className="input" />
                        </div>
                    </div>
                    <div className="field">
                        <label className="label"> Mot de passe </label>
                        <div className="control">
                        <input type="password"
                               ref="password"
                               name="password"
                               value={this.state.password}
                               onChange={this.onChange.bind(this)}
                               className="input" />
                        </div>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Signup" className="button is-primary" />
                    </div>
                    <Link to={{ pathname: '/register' }}>Inscription</Link>
                </form>
            </div>
        );
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(authActions, dispatch)
    };
}

export default connect(null, mapDispatchToProps)(LoginForm);

认证:

import { browserHistory } from 'react-router';
import * as types from './types';
import sessionApi from '../api/SessionApi';

export function loginSuccess(userData) {
    return {
        type: types.LOG_IN_SUCCESS,
        payload: userData
    }
}

export function loginFailed() {
    return {
        type: types.LOG_IN_FAILED
    }
}

export function logInUser(credentials) {
    return function(dispatch) {
        return sessionApi.login(credentials)
            .then(response => {
                console.log(response);
                if(response.data) {
                    sessionStorage.setItem('jwt', response.data.authentication_token);
                    dispatch(loginSuccess(response.data));
                    browserHistory.push('/dashboard/' + response.data.id);
                } else {
                    dispatch(loginFailed());
                }
            })
            .catch(error => {
                throw(error);
            })
    }
}

API:

import axios from 'axios';

class SessionApi {
    static login(credentials) {
        return axios.post('<link_hidden>', credentials)
        .then(response => {
            console.log(response);
            return response;
        })
        .catch(error => {
            return error;
        });            
    }
}

export default SessionApi;

会话缩减器(我有一个用于combineReducer的rootReducer):

import * as types from '../actions/types';
import initialState from './initialState';

export default function sessionReducer(state = initialState, action) {
    switch(action.type) {
        case types.LOG_IN_SUCCESS:
        console.log(action);
            return {
                ...state,
                userData: action.payload
            }
        case types.LOG_IN_FAILED:
            console.log('login failed');
            break;
        default:
            return state;
    }
}

和initialState文件:

export default {
    session: !!sessionStorage.jwt,
    userData: {}
}

有人知道为什么userData对象仍然是空的吗?在会话缩减器中,我传递了userData,所以我不明白..

修改

dashboard.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class Dashboard extends Component {
    constructor(props) {
        super(props);
        console.log(props);
    }

    render() {
        return(
            <div>
                <h1> Hello user </h1>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const userData = state.sessionReducer.userData;
    return { userData };
}

export default connect(mapStateToProps)(Dashboard);

2 个答案:

答案 0 :(得分:0)

你的代码对我来说似乎没问题。你能检查一下你的路由器是否正常工作吗?

答案 1 :(得分:0)

尝试将您的userData更改为数组,我认为您的有效负载可能是对象数组。那就是:

kubectl -n your-namespace get pods -o go-template='{{range $index, $element := .items}}{{range .status.containerStatuses}}{{if .ready}}{{$element.metadata.name}}{{"\n"}}{{end}}{{end}}{{end}}'

kubectl -n your-namespace get pods -o jsonpath='{range .items[*]}{.status.containerStatuses[*].ready.true}{.metadata.name}{ "\n"}{end}'