简体   繁体   English

React Reducer没有更新状态

[英]React Reducer is not updating State

I was driven crazy by my first react-redux app. 我的第一个react-redux应用使我发疯。 My Redux State is never updated. 我的Redux状态永远不会更新。 I tried to find every solution on the website but they are not helping. 我试图在网站上找到所有解决方案,但它们无济于事。 One very similar question here used promise but I am not. 一个非常相似的问题在这里使用了promise但我没有。 Redux-dev-tools catch the actions about the login_success but the global state is never updated, please tell me what should I do to debug if you could, thank you so much. Redux-dev-tools捕获了有关login_successactions ,但是全局状态从未更新,如果可以的话,请告诉我应该怎么做调试,非常感谢。

First Index.js 第一Index.js

import ... from ... 
const compostEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    const rootReducer = combineReducers({
        auth: authReducer,
    })
    const store = createStore(rootReducer, compostEnhancer(
        applyMiddleware(thunk)
    ));

const app = (<BrowserRouter><App /></BrowserRouter>)

ReactDOM.render(<Provider store={store}>{app}</Provider>, document.getElementById('root'));
registerServiceWorker();

authReducer.js : authReducer.js:

import * as actionTypes from '../actions/actionTypes';


const initialState = {
    token: null,
    userId: null,
    error: null,
    loading: false
}

const authReducer = (state = initialState, action) => {
    switch (action.types) {
        case actionTypes.LOGIN_START:
            return {
                ...state,
            };

        case actionTypes.LOGIN_SUCCESS:
            return {
                ...state,
                token: action.idToken,
                userId: action.userId,
                loading: false,
                error:null
            }
        default:
            return state;
    }
}

export default authReducer;

authAction.js: authAction.js:

import * as actionTypes from './actionTypes';
import axios from 'axios';

export const loginStart= () =>{
    return {
        type: actionTypes.LOGIN_START
    };
}

export const loginSuccess = (token,userId) =>{
    return {
        type: actionTypes.LOGIN_SUCCESS,
        userId: userId,
        idtoken: token,
    }
}

export const loginFail = (error) =>{
    return {
        type:actionTypes.LOGIN_FAIL,
        error:error
    }
}

export const auth = (email,password,isSignup ) =>{
    return dispatch =>{
        dispatch(loginStart());
        const authData = {
            email: email,
            password: password,
            returnSecureToken:true
        }
        let url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=...'
        if(!isSignup ){
            url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=...'
        }
        axios.post(url, authData)
            .then( response =>{
                console.log(response);
                dispatch(loginSuccess(response.data.idToken, response.data.localId))
            })
            .catch(err=>{
                console.log(err);
                dispatch(loginFail(err));
            })
    }
}

Login.js (Component): Login.js(组件):

 import ... from ...;

    class Login extends Component {
        constructor(props) {
            super(props);
            this.state = {
                email: "",
                password: "",
                isSignup: false,

            }
            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }
        handleSubmit = e => {
            e.preventDefault();
         // This will trigger actions
            this.props.onAuth(this.state.email, this.state.password, this.state.isSignup);  
            console.log(this.props.token) //here I can Get Token 
        }

        handleChange = (e) => {
            this.setState({ [e.target.name]: e.target.value });
        }

        render() {

            let form =
                <div className={classes.ContactData} >
                    <h4>Sign IN</h4>
                    <form onSubmit={this.handleSubmit} >
                        <Input
                            elementType='input'
                            name="email"
                            required
                            label="Email"
                            placeholder="Email"
                            value={this.state.email}
                            margin="normal"
                            onChange={this.handleChange}

                        />

                        <br />
                        <Input
                            elementType='input'

                            required
                            name="password"
                            value={this.state.password}
                            label="Password"
                            onChange={this.handleChange}
                        />

                        <br />
                        <Button
                            color="primary"
                            type="submit"
                        >Submit</Button>
                        <Button color="primary" href="/"> CANCLE</Button>
                    </form>

                </div>

            if (this.props.loading) {
                form = <Spinner />
            }

            let errorMessage = null;
            if (this.props.error) {
                errorMessage =(
                    <p>{this.props.error.message} </p>
                )

            }

            let token = null;
            if(this.props.token){
                token = this.props.token.toString()
            }

            return (
                <div>
                {errorMessage}
                { form }
                </div>
            )
        }
    }


    const mapStateToProps = state => {
        return {
            loading: state.auth.loading,
            error: state.auth.error,
            token:state.auth.idToken,

        }
    }

    const mapDispatchToProps = dispatch => {
        return {
            onAuth: (email, password, isSignup) => dispatch(actions.auth(email, password, isSignup)),

        }
    }

    export default connect(mapStateToProps, mapDispatchToProps)(Login);

And also, the problem leads to my Spinner and show ErrorMessage not working. 而且,问题导致我的Spinner显示错误ErrorMessage不起作用。

I suppose its a typo. 我想是错字了。

instead of 代替

switch (action.types) 

try this 尝试这个

switch (action.type) 

In reducer, we get an object returned from the actions, on the argument action . 在reducer中,我们从action返回一个对象,该对象为action

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM