我有一个组件ImageGallery
,在那里我想在按下Load More
按钮后加载更多图像。loadMore()
函数更新一个react-reduxglobalState.js
initialState值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>
</>
);
}
您的代码将无法工作,因为它是异步运行的,所以当您调用fetchImages
state时尚未更新。
我建议在依赖于limit
的useEffect
函数中使用fetchImages
。
loadMore
将触发redux状态更新,特别是limit
更新,因此useEffect
将再次运行。
const loadMore = () => {
dispatch(incrementLimitGallery());
};
和类似的
useEffect(() => {
fetchImages();
}, [limit]);
你可以像这样modify
你的loadmore函数:
const loadMore = async () => {
dispatch(incrementLimitGallery())
.then(()=>{
await fetchImages();
});
};
由于问题是,当您在distpatch
函数之后的fetching
images
时,您的redux
状态是not
更新的(因为调度是async
任务)。因此,当redux
状态为updated
时,可以运行fetchImages
函数。使用.then
方法实现logic
,如上图所示。