React Redux не обновляет состояние - PullRequest
0 голосов
/ 20 сентября 2019

Я ищу пару дней и не могу понять, почему redux не обновляет состояние. Я не вижу проблем в своем коде, пожалуйста, помогите мне найти проблему.

itэто простой проект входа в систему.Я вижу, что данные изменяются внутри редуктора при отладке, но они не сопоставляются с реквизитами и состояние не меняется.

это мой код:

actions.js

import {
    LOGIN_SUCCESS,
    LOGIN_FAILURE,
} from './types'

export const loginSuccess = (user) => ({
    type: LOGIN_SUCCESS,
    payload: user
})

export const loginFailure = (error) => ({
    type: LOGIN_FAILURE,
    payload: error
})

loginReducer.js

import {
    LOGIN_SUCCESS,
    LOGIN_FAILURE,
} from './types'

const initialState = {
    user: null,
    errorMessage: null
}


export const loginReducer = (state = initialState, action) => {
    switch (action.type) {
        case LOGIN_SUCCESS:
            return {...state,user: action.payload, errorMessage: null }
        case LOGIN_FAILURE:
            return {...state,errorMessage: action.payload }
        default:
            return state;
    }
}

loginScreen.js

import React from 'react'
import {
    Text,
    View,
    ImageBackground,
    Button,
    StyleSheet
} from 'react-native'
import { TextField } from 'react-native-material-textfield';
import { loginSuccess, loginFailure } from './reduxx/actions'
import { connect } from "react-redux";

class LoginScreen extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            email: "",
            password: "",
        }
    }

    _handlePress() {
        this.props.login(this.state.email, this.state.password)

        // user in propa is undifined 
        this.props.user
    }

    render() {

        let { email, password } = this.state

        return (
            <ImageBackground source={require('./images/loginBackground.jpg')} style={styles.imageBackground}>
                <View style={styles.mainContainer}>
                    <View style={styles.box}>
                        <TextField label="Email" value={email} onChangeText={email => this.setState({ email })} />
                        <TextField label="Password" textContentType="password" value={password} onChangeText={password => this.setState({ password })} />
                        <Button onPress={() => {

                            this._handlePress()

                        }} color="green" title="Sign in" style={styles.button} />
                    </View>

                    <View style={styles.bottomTextContainer}>
                        <Text style={{ color: "white" }}>Don't have an account?</Text>
                        <Text style={{ color: "lightgreen" }} onPress={() => this.props.navigation.navigate("Register")}> Sign up</Text>
                    </View>
                </View>
            </ImageBackground>
        )
    }
}

function mapStateToProps(state) {
    return {
        user: state.user,
        errorMessage: state.errorMessage
    }
}

function mapDispatchToProps(dispatch) {
    return {
        login: (email, password) => {
            try {
                let user = //get user from database
                dispatch(loginSuccess(user))
            } catch (error) {
                dispatch(loginFailure(error))
            }
        },
    }
}

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

const styles = StyleSheet.create({
    imageBackground: {
        width: '100%',
        height: '100%'
    },
    mainContainer: {
        flex: 1,
        justifyContent: "center"
    },
    box: {
        backgroundColor: 'white',
        padding: 8,
        margin: 8
    },
    button: {
        margin: 10
    },
    bottomTextContainer: {
        position: "absolute",
        bottom: 8,
        alignSelf: "center",
        flexDirection: "row"
    }
});

app.js

import React from 'react';
import { Provider } from "react-redux"
import store from "./reduxx/store";
import AppContainer from './Navigator'

export default class App extends React.Component {

  render() {
    return (
      <Provider store={store} >
        <AppContainer />
      </Provider>
    );
  }
}

store.js

import {createStore} from "redux";
import { combineReducers } from 'redux';
import {loginReducer} from './loginReducer'

const rootReducer = combineReducers({
    loginReducer,
  });

export default store = createStore(rootReducer)

Ответы [ 2 ]

1 голос
/ 21 сентября 2019

Состояние, которое входит в mapStateToProps, содержит все объединенные редукторы, поэтому нам необходимо получить доступ к имени редуктора сначала из состояния (например, state.loginReducer.user), прежде чем пытаться получить доступ к данным этого редуктора.Код PFB, который должен работать:

function mapStateToProps(state) {
    return {
        user: state.loginReducer.user,
        errorMessage: state.loginReducer.errorMessage
    }
}
1 голос
/ 21 сентября 2019

Изменить здесь:

function mapStateToProps(state) {
    return {
        user: state.user,
        errorMessage: state.errorMessage
    }
}

ДО

function mapStateToProps(state) {
    return {
        login: state.loginReducer
    }
}

А затем this.props.user до this.props.login.user и this.props.errorMessage до this.props.login.errorMessage во всехвхождение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...