状态更改后,mapStateToProps不会重新呈现组件

时间:2019-07-16 18:47:34

标签: react-native redux react-redux

我已经使用React / React-Native已有一段时间了,但是我是Redux的新手,所以我找不到问题。我有一个RESTFull API和两个主要模块:服务模型和价格模型。一旦管理员用户添加了新服务,该用户还可以为该服务关联价格。问题是,当我在NewServiceScreen中添加服务时,我的代码会调度一个操作来更改redux存储,从而更新NewPriceScreen上的服务列表,以使用户将价格与刚刚添加的服务相关联。

NewPriceScreen.js


function mapStateToProps(state){
    return {
        newPrice: state.newPriceReducer
    }
}

// Exports the connected NewPriceScreen
export default connect(mapStateToProps)(NewPriceScreen);

NewServiceScreen

...
handleSubmit = async() => {
        const { descricao } = this.props.newService;
        const userToken = await AsyncStorage.getItem('token');

        axios.post('/estabelecimento/servicos/',{descricao: descricao}, {
            headers: {
                "Authorization": `Token ${userToken}`
            }
        })
        .then(res => {
            Alert.alert(
                'Deu tudo certo :)',
                'Dados salvos com sucesso !',
            );
            console.log(res.data);
            this.props.dispatch({type: 'addService', newService: res.data});
        })
        .catch(error =>{
            Alert.alert(
                'Ops ! Algo aconteceu :(',
                error.message,
            );
        })
    }
...
const mapStateToProps = state => ({
    newService: state.newService
});

export default connect(mapStateToProps)(NewServiceScreen);

Reducers.js

const initialState = {
    servicos: [],
    // Database variables
    servico: 0,
    duracao: '',
    custo: '',
    comissao: ''
}

export default function newPriceReducer(state = initialState, action){
    // console.log("My state")
    // console.log(state);
    switch(action.type){
        case 'setState': {
            return {
                ...state,
                servico: action.descricao,
                duracao: action.duracao,
                custo: action.custo,
                comissao: action.comissao
            }
        }
        case "ADD_SERVICES": {
            // console.log("Servicos");
            const newState = {
                ...state,
                servicos: action.servicos
            }
            // console.log(newState);
            // console.log(newState === initialState)
            return newState;
        }
        case 'addService': {
            // console.log("ADD Service");

            servicos = state.servicos;
            servicos.push(action.newService);

            const newState = {
                ...state,
                servicos: servicos
            }

            // console.log(newState);
            // console.log(newState === initialState);
            return newState
        }
        default:
            return state;
    }

}

const initialState = {
    descricao: ''
}

export default function newServiceReducer(state = initialState, action){
    switch(action.type){
        case 'setDescricao': {
            return {
                ...state,
                descricao: action.descricao
            }
        }
        default:
            return state;
    }

}

App.js

import { createStore, applyMiddleware, combineReducers } from "redux";
import thunkMiddleware from 'redux-thunk'

import newServiceReducer from '../reducers/NewService';
import newPriceReducer from "../reducers/NewPrice";

import logger from 'redux-logger';

const mainReducer = combineReducers({
    newService: newServiceReducer,
    newPriceReducer
})

const store = createStore(mainReducer, applyMiddleware(logger));

export default store

import React from 'react';
import { Platform, StatusBar, StyleSheet, View, AsyncStorage, ImageBackground} from 'react-native';
import { AppLoading, Asset, Font, Icon } from 'expo';
import AppNavigator from './navigation/AppNavigator';

// Redux Stuff
import {Provider} from 'react-redux';
import AppStore from './store/App';

export default class App extends React.Component {
    state = {
        isLoadingComplete: false,
        isLoggedIn: false,
    };

    render() {
        if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
            return (
                <AppLoading
                    startAsync={this._loadResourcesAsync}
                    onError={this._handleLoadingError}
                    onFinish={this._handleFinishLoading}
                />
            );
        } else {
            return (
                <Provider store={AppStore}>
                    <ImageBackground source={require('./assets/images/back.png')} style={{width: '100%', height: '100%'}}>
                        {Platform.OS === 'ios' && <StatusBar barStyle="default" />}
                        <AppNavigator />
                    </ImageBackground>
                </Provider>
            );
        }
    }
}

1 个答案:

答案 0 :(得分:0)

行:

servicos = state.servicos;
servicos.push(action.newService);

我正在进行某种突变。我只是将其更改为:

const newState = {
    ...state,
    servicos: [...state.servicos, action.newService]
}