当状态改变时,React-Redux mapStateToProps不会触发

时间:2019-08-13 23:30:55

标签: reactjs redux

我正在学习Redux状态管理,并且遇到了问题。状态更改时,不会触发组件内的mapStateToProps。遍历了很多博客,无法找出问题所在。 商店似乎已正确更新,因为商店上的“订阅”方法会打印新更改。还要附上屏幕截图。

Actions.js

export const GET_ITEMS_SUCCESS = "GET_ITEMS_SUCCESS";
export const GET_ITEMS_FAILURE = "GET_ITEMS_FAILURE";
export const getItemsSuccess = (items) => ({
    type: GET_ITEMS_SUCCESS, payload: items
});
export const getItemsFailure = (error) => ({
    type: GET_ITEMS_FAILURE, error: error
}); 
export function getItems(dispatch) {
    return dispatch => {
    fetch(myList)
        .then(res => res.json())
        .then(res => {
            if(res.error) {
                throw(res.error);
            }
            store.dispatch(getItemsSuccess(res));
            return res;
        })
        .catch(error => {
            store.dispatch(getItemsFailure(error));
        })
   }
}

减速器

let initialState = {items: [], error: null}
function GetItemsReducer (state = initialState, action) {
    switch (action.type) {
        case GET_ITEMS_SUCCESS: 
           return Object.assign({}, state, {pending: false, items: action.payload});
       case GET_ITEMS_FAILURE:
           return Object.assign({}, state, {pending: false, error: action.error});
       default: 
           return state; 
    }
}
export default const rootReducer = combineReducers({
    GetItemsReducer: GetItemsReducer
});

商店

const mystore = createStore(rootReducer, applyMiddleware(thunk, promise));
mystore.subscribe(() => console.log("State Changed;", mystore.getState()));

组件

class Home extends Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        this.props.fetchItems();
    }
    render() {
       return (
          <div>{this.props.items.length}</div>
       )
    }
}
const mapStateToProps = (state) => {
   console.log('mapStateToProps ----------> ', state);
   return {
      items: state.GetItemsReducer.items,
      error: state.GetItemsReducer.error
   }
}
const mapDispatchToProps = (dispatch) => {
    return {
       fetchItems: bindActionCreators(getItems, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);

主要

class App extends React.Component {
    render() {
       return (
          <Provider store={mystore}>
             <Home />
          </Provider>
       )
   }
}
ReactDOM.render(<App />, document.querySelector("#app"))

enter image description here

谢谢。

0 个答案:

没有答案
相关问题