我使用的是反應和終極版,想知道是否以下是可能的:在設定初始狀態前等待Ajax調用反應,和/終極版
我在做一個「編輯表單」組件,我想設置初始狀態preselected
爲this.props.user.preselected.id。
我可以在任何地方撥打this.props.user.preselected.id
除了設置初始value.I不斷收到一個空值的情況下,我相信這是因爲減速this.props.user
只出現後this.props.fetchSingleUser
完成。
是否可以將初始狀態設置爲當前在同一個組件中提取的縮減器?
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;
}
我只是在我的行動的創建者添加。我認爲這是有道理的。您是否說我在獲取用戶並將其設置爲我的縮減器以顯示在組件中後應該派發另一個操作? – lost9123193
請問您還可以展示您的減速器嗎? – sylvain
當然我加了。 – lost9123193