Okey,在寻找解决方案几个小时后,我需要发布一个有关此问题的问题。
我已经读了x个线程并尝试“连接”组件与状态,不同的承诺回调,我尝试过setTimeout(大诺诺,我知道),我尝试更新componentDidMount,componentWillMount,componentDidUpdate等。我试过forceUpdate() 。实际上,状态是过时的,包含来自Firebase的更新数据的“产品列表”。好像组件在没有这些数据的情况下渲染。
从firebase获取数据的函数:
function updateProducts(endpointstring) {
let initialList = [];
let productsList = [];
function getData(endpoint) {
let productsRef = database.ref('products/' + endpoint);
return productsRef.once('value').then(function (snapshot) {
return snapshot.val()
})
}
Promise.all([getData(endpointstring)]).then( (response) => {
for(var product in response){
productsList.push(response[product])
console.log(productsList)
}
})
return productsList;
}
减速机:
import * as firebase from 'firebase';
const database = firebase.database();
function updateProducts(endpointstring) {
let initialList = [];
let productsList = [];
function getData(endpoint) {
let productsRef = database.ref('products/' + endpoint);
return productsRef.once('value').then(function (snapshot) {
let list = [];
for(var prod in snapshot.val()){
list.push(snapshot.val()[prod])
}
return list
})
}
var newList = getData('mobiles');
for(var product in newList){
productsList.push(newList[product])
console.log(productsList)
}
return getData('mobiles');;
}
const mobilesReducer = (state = {
view: "everything",
filteredValue: "",
productInFocus: 0,
products: updateProducts('mobiles'),
imgLoads: [],
loadedOnce: false,
priceRange: {min: 0, max: 3500},
minPrice: 0,
maxPrice: 3500,
sort: "popular"
}, action) => {
let newState = {...state};
switch(action.type){
case 'COMPONENT_DID_MOUNT':
console.log(action.payload)
action.payload.componentName === 'mobiles' ? newState = {...newState, products: action.payload.productList} : null;
return newState;
有人对此有不同看法吗?
感谢。