我正在尝试从Firebase数据库加载笔记。添加它们很好,并且检索我的笔记也很好(我可以通过console并通过console.firebase.google.com来检查我的Firebase数据库,以确认它是否正常工作。)
我在项目中第一次使用React-Redux。
我已经尝试调试并检查控制台记录变量是否显示了正确的数据。一切正常,但是什么也不会显示或更新。
App.js:
componentWillMount(){
const previousNotes = Array(0);
this.removeAuthListener = app.auth().onAuthStateChanged((user) => {
app.database().ref().child('notities').on('child_added', snap => {
if(snap.val().username === this.props.email){
console.log('DB_ADDED');
previousNotes.push({
id: snap.key,
noteContent: snap.val().noteContent,
modifiedDate: snap.val().modifiedDate
});
console.log("previousNotes", previousNotes);
store.dispatch({type: "DB_NOTE_ADDED", payload: { notes: previousNotes }});
}
});
NotesBody.js:
import React from 'react';
import { connect } from "react-redux";
class NotesBody extends React.Component {
render(){
return(
<ul>
{
this.props.notes.map((note) => {
return <li key={note.id}>{note.noteContent}</li>
})
}
</ul>
);
}
}
function mapStateToProps(state){
console.log("[STATE NOTESBODY]", state);
return {
notes: state.notes
}
}
export default connect(mapStateToProps)(NotesBody);
我的减速器:
import { createStore } from 'redux';
import { app } from '../config/config';
const initialState = {
database: app.database().ref().child('notities'),
notes: []
}
const reducer = (state = initialState, action) => {
console.log("Reducer running", action.type);
switch(action.type){
default:
break;
case "DB_NOTE_ADDED":
console.log("DB_NOTE_ADDED", action.payload.notes);
state = {
...state,
notes: action.payload.notes
}
break;
}
return state;
}
const store = createStore(reducer);
store.subscribe(() => {
console.log("Store updated", store.getState());
});
export default store;
当我的代码收到注释时,它将调用其中包含notes数组的调度函数:
var previousNotes = [
{ id: "1", noteContent: "Hoi" }
];
store.dispatch({type: "DB_NOTE_ADDED", payload: { notes: previousNotes }})
实际结果:
预期结果:
编辑:添加了我的操作代码。如果我实施以下第一个解决方案,则现在只加载了一个便笺。
答案 0 :(得分:2)
我建议在该NotesBody.js
组件上使用某种加载状态,直到您确定数据已成功存储为止。话虽如此,将loading: true
添加到您的redux状态,并且仅在成功获取笔记并更新状态时才将其设置为false
。
class NotesBody extends React.Component {
render() {
let notes = <p>Loading ...</p>;
if (!this.props.loading) {
notes = this.props.notes.map(note => (
<li key={note.id}>{note.noteContent}</li>
));
}
return <ul>{notes}</ul>;
}
}
function mapStateToProps(state) {
console.log("[STATE NOTESBODY]", state);
return {
notes: state.notes,
loading: state.loading
};
}
您的开关应如下所示:
switch(action.type){
default:
break;
case "DB_NOTE_ADDED":
console.log("DB_NOTE_ADDED", action.payload.notes);
state = {
...state,
notes: action.payload.notes,
loading: false
}
break;
}
PS。当您决定从API请求新笔记时,请不要忘记将加载切换为true。
答案 1 :(得分:0)
好吧开枪打我的脸..我设法使它以这种方式工作:
function mapStateToProps(state){
return {
notes: state.notes,
notesLength: state.notes.length
}
}
如果我添加了笔记长度以外的其他内容,问题又会再次出现。..