我在react 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 Pack的第一个实例中,我能够获取数据并能够正确呈现。但是,当我刷新同一页面时,数据会到达减速器(已设置状态),而不到达选择器(已进入状态)。页面刷新后如何将数据从reducer导入选择器?
答案 0 :(得分: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开发工具中?调试起来非常困难,而且我个人认为您的应用程序仅在首次加载时才能运行(如果您不管理任何缓存)。
希望这些反馈能帮助您缩小问题范围:)