useSelector不会更新UI

时间:2020-07-19 19:14:00

标签: reactjs redux react-hooks

我有一个嵌套状态,如:

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

现在我可以通过使用jobCards从父组件的道具中获得相应的detailsID,即useSelector

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

我有一个button,可以在parts中成功地在各个jobCards中添加新对象,但是不会更新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
            })
        }

2 个答案:

答案 0 :(得分:0)

这样使用

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 />
   </>
)

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

答案 1 :(得分:0)

我的代码中有一些可变性。 减速器应该是:

 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
            })
        }