gpt4 book ai didi

javascript - 即使没有调度任何操作,Redux 状态也会在加载时发生变化

转载 作者:行者123 更新时间:2023-11-28 18:16:16 25 4
gpt4 key购买 nike

由于某种原因,当我加载 web 应用程序时,即使没有调度任何操作,状态“currentView”也会设置为“subjects”而不是初始值“schools”。为什么会这样?

actions.js

export function showSubjects(schoolId) {
return {
type: 'SHOW_SUBJECTS',
schoolId
};
}

browse.js

const initialState = {
currentView: 'schools',
schools: [{id: 'AAAA', name: 'aaaa'}, {id: 'BBBB', name: 'bbbb'}],
subjects: [{id: 'CCC', name: 'ccc'}, {id: 'DDD', name: 'ddd'}]
};

function browse(state = initialState, action) {
switch (action.type) {
case 'SHOW_SUBJECTS':
return {
...state,
currentView: 'subjects'
};
default:
return state;
}
}

export default browse;

BrowseReduxContainer.jsx

import { connect } from 'react-redux';
import { showSubjects } from '../actions/actions';
import Browse from '../components/Browse.jsx';

function propsFilter(state) {
switch (state.currentView) {
case 'schools':
return state.schools;
case 'subjects':
return state.subjects;
default:
throw new Error(`No such view: ${state.currentView}`);
}
}

const mapStateToProps = (state) => ({
schools: propsFilter(state)
});

const mapDispatchToProps = (dispatch) => ({
showSubjects: (schoolId) => {
dispatch(showSubjects(schoolId));
}
});

const BrowseReduxContainer = connect(mapStateToProps, mapDispatchToProps)(Browse);

export default BrowseReduxContainer;

Browse.jsx

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

const Browse = (props) => (
<div>
{props.schools.map((school) => (
<RaisedButton key={school.id} label={school.name} onClick={props.showSubjects(school.id)} />
))}
</div>
);

export default Browse;

其他相关文件,如有需要,可以在这里查看:https://github.com/Joonpark13/serif.nu/tree/feature/browse

最佳答案

您的 RaisingButton 导致问题:

<RaisedButton key={school.id} label={school.name} onClick={props.showSubjects(school.id)} />

您可以在 onClick 处理程序中执行 showSubjects,而不是传递引用。相反,它应该是 onClick={() => props.showSubjects(school.id)} 以便该函数仅在点击后执行。

作为替代方案,您还可以修改 mapDispatchToProps:

const mapDispatchToProps = (dispatch) => ({
showSubjects: (schoolId) => () => {
dispatch(showSubjects(schoolId));
}
});

关于javascript - 即使没有调度任何操作,Redux 状态也会在加载时发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40710916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com