React - 从reducer编辑状态

时间:2018-03-15 22:17:49

标签: reactjs

使用ReactJS / Redux / thunk,我无法得到简单的示例工作。

我无法从reducer获取状态,或者我不知道如何访问它?

我结合了我的减速器:

import {combineReducers} from 'redux';
import sites from './sitesReducer';
import session from './sessionReducer';
import cities from './citiesReducer';

const rootReducer = combineReducers({
    // short hand property names
    sites,
    cities,
    session
})

export default rootReducer;

然后创建一个商店:

import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../reducers'
import thunk from 'redux-thunk';

export default function configureStore() {
    return createStore(
        rootReducer,
        applyMiddleware(thunk)
    );
}

在citiesReducer:

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

export default function citiesReducer(state = initialState.cities, action) {
    switch(action.type) {
        case types.AUTOCOMPLETE_CITIES_SUCCESS:
            // it works, data is filled from my action (from ajax get)
            console.log(action.data)

            // here I guess state is not updated, I can't get it in HomePage
            return {
                ...state,
                cities: action.data
            };
        default:
            return state;
    }
}

在我的index.js文件中,我使用router:

const store = configureStore();

render(
    <Provider store={store}>
        <Router history={history}>
            <div>
                <Route exact path="/" render={() => (
                    auth.loggedIn() ? (
                        <HomePage />
                    ) : (
                        <Redirect to="/login"/>
                    )
                )}/>
                ....

在HomePage.js中,我无法从上下文(?)获取存储,所以我使用configureStore:

const store = configureStore();

class HomePage extends React.Component {
    constructor(props, context) {
        super(props, context)
        // context is empty :(
        this.state = {
            value: ''
        }
    }
    render() {
        return (
            <TextInput
                value={value}
                onChange={(event, value) => {
                    this.setState({ value })
                    if (value.length > 2) {
                        // call ajax action, which works 
                        this.props.actions.getCityByName(value);
                    }
                }}
            />
            <ul>
                {store.getState().cities.map(function(city, index){
                    return <li key={ index }>{city.title}</li>;
                })}
            </ul>
        )
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(citiesActions, dispatch)
    };
}
export default connect(null, mapDispatchToProps)(HomePage);

HomePage中的 store.getState()。cities 永远不会更新。我也尝试使用 this.state.cities 。 是因为我无法从上下文访问商店吗?因为路由器?我使用react-router v4。或者我是否需要在我的HomePage组件中更新和访问状态?

对不起大代码。我试图最多减少(啊啊!)

0 个答案:

没有答案