如何在页面新鲜后从选择器获取状态?

问题描述 投票:1回答:1

我在反应JS样板代码中有一个容器组件,它使用sagas到reducer中获取数据(比如学校列表),并设置一个状态,由我的渲染页面中的选择器函数读取以显示给用户。

saga.js从服务器返回的示例数据

    data: [  {
                id: '1',
                name: 'School1',
                location: 'Location1',
             },
             {
                id: '2',
                name: 'School2',
                location: 'Location2',
             },
          ]

actions.js片段

    export function requestSchools() {
      return {
        type: REQUEST_SCHOOLS,
      };
    }
    export function requestSchoolsSucceeded(schoolsData) {
      return {
        type: REQUEST_SCHOOLS_SUCCEEDED,
        schoolsData,
      };
    }

reducer.js片段

    function schoolsContainerReducer(state = initialState, action) 
    {
      switch (action.type) {
        case REQUEST_SCHOOLS_SUCCEEDED:
           return state.set('schools', action.schoolsData);
        default:
           return state;
      }
    }

selector.js片段

    const makeSelectSchools = () =>
     createSelector(selectSchoolsContainerDomain, schoolState =>
     schoolState.get('schools'),
    );

index.js片段

    //This will trigger action REQUEST_SCHOOLS in action.js
    constructor(props) {
        super(props);
        this.props.requestSchools();
    }

    render() {
        const { schools } = this.props;

        const renderSch = schools.data.map(sch => (
          <div key={sch.id}>
            {sch.name} {sch.location}
          </div>
        ));
        return (
          <div>
            {renderSch}
          </div>
        );
      }

    const mapStateToProps = createStructuredSelector({
      schoolsContainer: makeSelectSchoolsContainer(),
      schools: makeSelectSchools(),
    });

    function mapDispatchToProps(dispatch) {
      return {
        //dispatch request schools action
        requestSchools: () => dispatch(requestSchools()),
      };
    }

在构建Web包的第一个实例中,我能够获取数据并能够正确呈现。但是,当我刷新同一页面时,数据会一直到reducer(设置状态)但不会到选择器(我到达状态)。如何在页面刷新后将reducer中的数据导入选择器?

javascript reactjs redux redux-saga selectors-api
1个回答
1
投票

首先,尝试不使用componentWillMount方法,因为它被React弃用(https://reactjs.org/docs/react-component.html#unsafe_componentwillmount

我不明白为什么它不能用于刷新。您可能不需要将选择器作为函数,也许您需要一个默认值来确保您在React中执行的映射的有效性(也许这是问题吗?)

const makeSelectSchools = createSelector(
  selectSchoolsContainerDomain, // What is this doing? Getting the state of the previous reducer right?
  schoolState => schoolState.get('schools') || [],
);

然后在容器中调用它:

const mapStateToProps = createStructuredSelector({ schools: makeSelectSchools });

您确定控制台中没有更多日志吗?还是在redux开发工具?现在调试非常困难,我个人认为你的应用程序只有在第一次加载时才有效(如果你不管理任何缓存)。

希望这些小反馈将帮助您缩小您的问题范围:)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.