React Redux没有实时更新组件状态



我有一个组件ImageGallery,在那里我想在按下Load More按钮后加载更多图像。loadMore()函数更新一个react-reduxglobalState.jsinitialState值limit。但是,当我按下Load More按钮时,我必须第一次按2次才能获得第一个16图像。之后,它按预期更新值。但是,第一次我必须按2次。但是,我想,它将工作在第一次点击,并获得16项目等。

globalState.js:

export const globalState = createSlice({
name: "global",
initialState: {
limit: 8
}
reducers: {
// imageGallery
incrementLimitGallery: (state) => {
state.limit += 8;
},
},
});

组件ImageGallery.jsx:

let API = "https://www.example.com/images/";
export default function ImageGallery() {
const dispatch = useDispatch();
const limit = useSelector((state) => state.global.limit);
const [images, setimages] = useState(null);
async function fetchImages() {
const response = await axios.get(API + limit);
if ("error" in response.data) {
setimages(null);
} else {
setimages(response.data);
}
}
const loadMore = async () => {
dispatch(incrementLimitGallery());
await fetchImages();
};
return (
<>
//implementation of image gallery, long code so hide it
<div>{images ? (imgaes.map(image => (.......))): null}</div>
<div>
<button onClick={() => loadMore()}>Load More</button>
</div>
</>
);
}

您的代码将无法工作,因为它是异步运行的,所以当您调用fetchImagesstate时尚未更新。

我建议在依赖于limituseEffect函数中使用fetchImages

另一方面,loadMore将触发redux状态更新,特别是limit更新,因此useEffect将再次运行。
const loadMore = () => {
dispatch(incrementLimitGallery());
};

和类似的

useEffect(() => {
fetchImages();
}, [limit]);

你可以像这样modify你的loadmore函数:

const loadMore = async () => {
dispatch(incrementLimitGallery())
.then(()=>{
await fetchImages();
});
};

由于问题是,当您在distpatch函数之后的fetchingimages时,您的redux状态是not更新的(因为调度是async任务)。因此,当redux状态为updated时,可以运行fetchImages函数。使用.then方法实现logic,如上图所示。

最新更新