我有一个包含2个元素的数组来渲染ItemComponent
在ListComponent
中,我调度调用api并获得2个差分图像以在存储中设置可变image
const ListComponent = (array) => {
const dispatch = useDispatch()
return array.map((item,index) => {
dispatch(
//dispatch call api, set value image in store
getImage(item...)
)
return <ItemComponent />
})
}
const ItemComponent = () => {
const {image} = useSelector(...)
return (
<img src={image}} />
)
}
//Reducer
let inintitalState = {
image: "",
};
export function Image(state = inintitalState, action) {
switch (action.type) {
case "GET_IMAGE":
return { ...state, image: action.data };
default:
return { ...state };
}
}
//Action
export function getImage(item...) {
return async(dispatch)=> {
try{
const res = axios("GET", URL(item...))
dispatch({type:"GET_IMAGE", res})
}
catch(error){
console.log(error)
}
}}
结果是标签img
在ItemComponent
中会显示相同的图像,我想让它呈现差异图像
dispatch需要在ListComponent中使用,因为它需要参数
请引导我
它应该工作:
let inintitalState = {
image: [],
};
export function Image(state = inintitalState, action) {
switch (action.type) {
case "GET_IMAGE":
return { ...state, image: [...state.image, action.data] };
default:
return { ...state };
}
}
现在图像将是一个阵列,它应该是地图
const {image} = useSelector(...)