我正在使用react和redux,并且想知道以下是否可能:
我正在创建一个“编辑表单”组件,我想将preselected
的初始状态设置为this.props.user.preselected.id。
我可以在任何地方调用this.props.user.preselected.id
,除了设置初始值的情况。我一直得到一个空值,我相信这是因为缩减器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;
}
答案 0 :(得分:1)
Verry的常见方法是为异步操作提供3个操作
<强> types.js 强>
export const FETCH_USER_REQUEST = 'FETCH_USER_REQUEST'
export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS'
export const FETCH_USER_FAIL = 'FETCH_USER_FAIL'
<强> reducer.js 强>
import {combineReducers} from 'redux';
import * as types from './types';
const isFetching = (state = false, action) => {
switch (action.type) {
case types.FETCH_USER_REQUEST:
return true;
case types.FETCH_USER_SUCCESS:
case types.FETCH_USER_FAIL:
return false;
default:
return state;
}
};
const data = (state = {}, action) => {
switch (action.type) {
case types.FETCH_USER_SUCCESS:
return action.payload.data;
}
return state;
};
export default combineReducers({
isFetching,
data
});
因此,您可以在组件中获得isFetching
道具并显示/隐藏您的表单
答案 1 :(得分:0)
您认为只有在收到用户数据后才能呈现表单吗?
USER_LOADED
。userLoaded = true
user.loaded
以显示表单