如果你有兩個name
,你通過點擊添加列表id
,那麼它可能是正確的addList處理程序中完成:
addList(name, id) { // bound with click
const size = this.props.lists.length
this.props.addList(name)
if(!size) {
this.props.selectList(id)
}
}
否則,你需要等待創建列表(獲取id
),然後調度selectList操作。最髒的解決方案可能只是:
addList(name) { // bound with click
const size = this.props.lists.length
this.props.addList(name)
if(!size) {
// don't do that! it's just for proof of concept
setTimeout(() => this.props.selectList(this.props.lists[size].id))
}
}
的進一步深入,你可以使用componentWillReceiveProps
鉤抓lists.length
becames 1,然後觸發selectList
正常:
componentWillReceiveProps(nextProps) {
const previousSize = this.props.lists.length
const size = nextProps.lists.length
if(previousSize === 0 && size === 1) {
this.props.selectList(nextProps.lists[size].id))
}
}
另一種辦法是減速,我們不要沒有處理新列表id
,但僅與之前的列表大小(並且不需要額外的動作觸發器):
case ADD_LIST:
return {...state,
lists: [...state.lists,
action.newList
],
selectList: {...state.selectList,
list: !state.lists.length ? action.newList : state.selectList.list
}
}
最後,而不是所有以上,動作創造者(最喜歡的一個對我來說):
export function addList(name) {
return (dispatch, getState) => {
const size = getState().lists.length
const newList = generateNewListByName(name)
dispatch({
type: ADD_LIST,
newList
})
if(size === 0)
dispatch({
type: CHANGE_SELECTED_LIST,
selectedListId: newList.id
})
}
}
}
最後PICE需要適應您的基礎設施,但主要的想法是一樣的:做一些邏輯由以前的一些狀態條件(size === 0
)。
但如果我不使用類組件,並且無法訪問componentWillReceiveProps,但功能組件? – serj
@serj我給aswer增加了一些想法,它們可以應用於功能組件的情況。 – dhilt