#reactjs #react-native #redux #react-redux-firebase
#reactjs #react-native #redux #react-redux-firebase
Вопрос:
Я пытаюсь сопоставить свою коллекцию подарков в firestore с моим реквизитом в Shop.js , но firestoreConnect ничего не делает. Когда я распечатываю state.firestore.ordered в mapStateToProps, я получаю Object{} , а state.firestore.ordered.giveaways не определено.
Что-то не так с моей конфигурацией? Документация по react-redux-firebase делает вид, что все здесь.
Shop.js
const giveaways = state.firestore.ordered.giveaways;
console.log("=====================================================");
console.log(giveaways);
return {
profile: state.firebase.profile,
giveaways: state.firestore.ordered.giveaways
}
}
export default compose (
firestoreConnect(() =>{
{collection: 'femaleClothes'}
}),
connect(mapStateToProps),
)(Shop);
fbConfig.js выглядит примерно так
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
var firebaseConfig = { /*firebase config information*/};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//firebase.analytics();
firebase.firestore();
export default firebase;
и соответствующие части App.js
const store = createStore(rootReducer,
compose(
applyMiddleware(thunk.withExtraArgument({getFirebase,getFirestore})),
reduxFirestore(fbConfig)
)
);
const rrfConfig = {
userProfile: 'users',
useFirestoreForProfile: true
}
const rrfProps = {
firebase,
config: rrfConfig,
dispatch: store.dispatch,
createFirestoreInstance,
}
export default function App() {
return (
<Provider store={store}>
<ReactReduxFirebaseProvider {...rrfProps}>
<AuthIsLoaded>
<NavigationContainer>
<AuthNavigator/>
</NavigationContainer>
</AuthIsLoaded>
</ReactReduxFirebaseProvider>
</Provider>
);
};
Комментарии:
1. Возможно ли, что это должно быть
state.firebase.ordered
вместоstate.firestore.ordered
?
Ответ №1:
Я не смог увидеть ошибку в вашей конфигурации. Недавно у меня были такие же проблемы, и, наконец, мне удалось их решить. Вот mapStateToProps и экспорт:
const mapStateToProps = (state) => {
return {
sections: state.firestore.ordered.sections,
auth: state.firebase.auth
}
}
export default compose(
connect(mapStateToProps),
firestoreConnect(
[{collection: 'sections'}]
)
)(ShowSection);
Для использования в вашем компоненте:
//if it's functional component
//const section = props.section
//if it's class component (I mention it just in case)
const sections = this.props.sections
// in my render method, make sure the sections is fetched
{sections amp;amp; sections.map( section =>{
return <Template
key={section.id}
title={section.title}
icon="edit"
link={`/section/${section.id}`}
btnTxt="Rediger"
info={section.info}
></Template>
})}
Я также пробовал в другом проекте, и проблема заключалась в том, как вы упомянули: section.map() не является функцией. Это из-за возвращаемого объекта. После этого просто консоль.зарегистрируйте возвращаемый объект. Если это массив, этот метод .map() будет работать. Но если это объект JS, .map или .forEach не будут работать. Вместо этих методов вы должны выполнить итерацию вашего объекта следующим образом:
//func component
const Overview = (props) => {
const sections = props.sections
return(
<div>
{sections amp;amp; Object.entries(sections).map(section =>(
//items id
<h1>{section[0]}</h1>
//items keys (whatever you have in your collection's document's fields)
<h1>{section[1].title}</h1>
<h1>{section[1].info}</h1>
))}
</div>
)
}
Но проблема с react-redux-firebase v.3.0.0, в документации говорится, что:
export default compose(
firestoreConnect(() => ['todos']), // sync todos collection from Firestore into redux
connect((state) => ({
todosList: state.firestore.data.todos
})
)(SomeComponent)
Я хочу подчеркнуть это: state.firestore.data.todos Более старой версией было state.firestore.todos
Я попытался объяснить проблему и решение, и я надеюсь, что это поможет.