【发布时间】:2025-12-23 07:20:15
【问题描述】:
我正在使用 react 和 redux,想知道以下是否可行:
我正在制作一个“编辑表单”组件,我想将 preselected 的初始状态设置为 this.props.user.preselected.id。
除了设置初始值的情况外,我可以在任何地方调用this.props.user.preselected.id。我一直得到一个空值,我相信这是因为reducer this.props.user 仅在this.props.fetchSingleUser 完成后出现。
是否可以将初始状态设置为当前在同一组件中获取的 reducer?
class PropertyEdit extends Component {
static contextTypes = {
router: PropTypes.object
};
constructor(props) {
super(props);
this.state = {
preselected= this.props.user.preselected.id
};
}
componentWillMount() {
this.props.fetchSingleUser(this.props.params.id);
}
....
function mapStateToProps(state) {
return {
user:state.user.single
};
}
function mapStateToProps(state) {
return {
user:state.users.single
};
}
action.js
export function fetchSingleUser(id) {
return function(dispatch) {
axios.get(`${URL}/users/${id}`)
.then(response => {
dispatch({
type:FETCH_USER,
payload: response
});
})
.catch(() => {
console.log("Error ");
});
}
}
减速器:
const INITIAL_STATE = { single: null };
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_USER:
return {...state, single: action.payload.data};
}
return state;
}
【问题讨论】: