连接在react-redux中不起作用并且不重新渲染

时间:2020-06-24 05:31:02

标签: reactjs redux react-redux

我正在一个React项目上,在这个项目中,我创建了一个带有多个reducer的redux存储

import { createStore, combineReducers } from "redux"
import HsPageDataReducer from "../reducers/HsPageDataReducer.jsx"
import HsUserDataReducer from "../reducers/HsUserDataReducer.jsx"

export default function HsGlobalStore() {
    return createStore(combineReducers({
        PageDataReducer: HsPageDataReducer,
        UserDataReducer: HsUserDataReducer
    }));
}

我正在使用connect函数为组件提供状态

const mapStateToProps = function myMapStateToProps(state) {
    return {
        page_display_name: state.PageDataReducer.page.page_data.page_display_name,
        page_name: state.PageDataReducer.page.page_data.page_name
    }
}

const NewHsPageHadNameIdAreaBox = connect(mapStateToProps)(HsPageHadNameIdAreaBox);


const id = "page_had_name_id_area_box";

if (document.getElementById(id) !== null) {
    ReactDOM.render(<Provider store={HsGlobalStore()}> <NewHsPageHadNameIdAreaBox />  </Provider>, document.getElementById(id));
}

export default NewHsPageHadNameIdAreaBox;

这是我在HsPageDataReducer中的动作处理程序

        const initialState = {
            page : HsPageDataObj()
        }
        
        
        export default function HsPageDataReducer(state = initialState, action) {
    try {
        switch (action.type) {
            case HsPageDataActionConst.GET_PAGE_FULL_DATA_BY_PAGE_NAME:
                return new HsPageGetPageFullDataAction().getData(action.pageName, state)
                    .then((newState) => { console.log(newState.page.page_data.page_display_name);  return newState }).catch((newState) => { return state});
            default:
                return state;
        }
    } catch (e) {
        return state;
    }
}

最初,一切运行正常

当我从组件分派动作时

componentDidMount() {
        this.goForGetPageData();
    }

    goForGetPageData() {
        this.props.dispatch({
            pageName: "sdevpura5",
            type: HsPageDataActionConst.GET_PAGE_FULL_DATA_BY_PAGE_NAME
        });
    }

正在获取数据

Test Data Image

但不重新渲染组件。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试以下代码可能会有所帮助。因为我使用此代码重新渲染了组件

    resetPage() {
     ReactDOM.unmountComponentAtNode(document.getElementById('addVitalSettingComponentId'));
     AddVitalSettingComponent = ReactDOM.render(
      <AddVitalSettingComponent />, document.getElementById('addVitalSettingComponentId')
     );
}

答案 1 :(得分:0)

Reducer应该是纯函数,您正在那里进行api调用:)

您需要使用redux-thunkredux-saga之类的中间件。

阅读一些信息here并检查thisthis codesandbox example