useSelector不会更新UI



我有一个嵌套状态,如:

bookingDetails = {
jobCards: [
{
details_id: '1',
parts: [
{...},
{...}
]
}
]}

现在,我通过使用useSelector:从父组件(即detailsID(的props中获得组件中相应的jobCards

const jobCard = useSelector(state => state.bookingDetails.jobCards.find(item => item.details_id === detailsID))

我得到了一个button,它成功地在相应的jobCards中的parts中添加了新对象,但它没有更新UI。我的bookingDetails减速器:

case 'ADD_PARTS':
return {
...state,
jobCards: state.jobCards.map(jobCard => {
if (jobCard.details_id === action.id) {
jobCard.parts = [...jobCard.parts, { _id: uuid(), name: '' }]
}
return jobCard
})
}

像这样使用

const [isJobUpdated, setIsJobUpdated] = useState(false);
const jobCard = useSelector(state => state.bookingDetails.jobCards.find(item => item.details_id === detailsID))
useEffect(() => {
setIsJobUpdated(!!jobCard.length);
}, [jobCard])
return (
<>
{isJobUpdated && <YourComponent />
</>
)

注意:这不是最好的方法。您可能会面临重新渲染的问题。只是为了检查这是否解决了您当前的问题。

忘记添加返回语句。减速器应该是:

case 'ADD_PARTS':
return {
...state,
jobCards: state.jobCards.map(jobCard => {
if (jobCard.details_id === action.id) {
return {
...jobCard,
parts: [...jobCard.parts, { id: uuid(), name: ''}]
}
}
return jobCard
})
}

相关内容

  • 没有找到相关文章

最新更新