如何解决信息会在Redux商店提供之前呈现吗?
我正在用React,Redux和Firebase(Firestore + Storage)建立一个电子商务商店。 在 App 组件中,信息将从Firebase中获取并分发。然后在API调用完成后 Fetch_Products_Pending 动作 Fetch_Products_Success 。
我的UI组件在分派 Fetch_Products_Success 操作之前从Firestore渲染信息。我不知道从何处获取此信息,因为唯一的方法是通过App组件中的 fetchData 函数。
因此,该组件使用 Fetch_Products_Success 完成之前的信息进行呈现,因此没有图像的URL。 Fetch_Products_Success 之后,尽管道具发生了更改,但它不会重新呈现(因为现在已获取URL)。
如果我重新路由到页面,则图像会正确显示。
App.js
const App = props => {
const dispatch = useDispatch();
useEffect(() => {
const storageRef = storage.ref();
const arr = [];
dispatch(fetchProductsPending());
//API Call to fetch information from Firestore
async function fetchData() {
try {
await firestore
.collection("necklaces")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
arr.push(doc.data());
});
});
//Async forEach loop
const asyncForEach = async (array,callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index],index,array)
}
}
//Adding the URL to the products object that is afterwards saved in the Redux store[![enter image description here][1]][1]
const start = async () => {
await asyncForEach(arr,async (item) => {
await storageRef.child(`images/${item.name}/1.png`).getDownloadURL().then(function(url) {
return (
item.url = url
)
});
})
}
start();
dispatch(fetchProductsSuccess(arr));
} catch (err) {
dispatch(fetchProductsError(err));
}
}
fetchData();
},[])
Shop.js
const mapState = ({ products }) => ({
products: products.products,pending: products.pending
});
const Shop = props => {
const { products,pending } = useSelector(mapState);
return (
<>
<div className="row">
{products.map((item,index) => {
console.log(item)
return (
<ShopItems
name={item.name}
price={item.price}
key={index}
id={item.id}
url={item.url}
/>
);
})}
</>
ShopItems.js
const ShopItems = props => {
return (
<div className="article">
<Link className="items" to={`/article/${props.id}`}>
<img className="itemPicture" src={props.url} alt=""/>
<h6>{props.name}</h6>
<h6>{props.price}€</h6>
</Link>
</div>
)
}
现在我的Redux代码
Actions.js
export function fetchProductsPending() {
return {
type: productTypes.FETCH_PRODUCTS_PENDING
}
}
export function fetchProductsSuccess(products) {
return {
type: productTypes.FETCH_PRODUCTS_SUCCESS,payload: products
}
}
export function fetchProductsError(error) {
return {
type: productTypes.FETCH_PRODUCTS_ERROR,payload: error
}
}
Reducer.js
const INITIAL_STATE = {
pending: false,products: [],error: null
}
export function productsReducer(state = INITIAL_STATE,action) {
switch(action.type) {
case productTypes.FETCH_PRODUCTS_PENDING:
return {
...state,pending: true
}
case productTypes.FETCH_PRODUCTS_SUCCESS:
return {
...state,pending: false,products: action.payload
}
case productTypes.FETCH_PRODUCTS_ERROR:
return {
...state,error: action.error
}
default:
return state;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。