所以我在使用 React、Firebase 和 Node 创建的这个基本任务应用程序方面遇到了一个小问题。我在 heroku 上托管了工作版本(将在下面发布链接),因此您可以使用它来了解我的意思。
我的问题
如果您访问我的应用程序的链接,您会看到当您最初单击“获取任务”按钮时,任务不会加载到屏幕上。需要单击两次才能将列表填充到屏幕上。
此外,当您单击关闭图标以尝试删除特定任务时,好吧......您将亲眼看到发生了什么,哈哈。
我的想法 尽管我很高兴它至少可以工作,但我觉得罪魁祸首似乎是我在 grabTasks 函数内部创建的代码。不要问我为什么用变量名 x 创建一个随机空数组,我也不知道,这是我让它工作的唯一方法。我已经阅读了所有的 firebase 文档,所以我希望这里有人可以启发我了解问题所在,并可能提出更好的解决方法。下面的代码和链接。
App.js
// App.js
export default class App extends Component {
constructor(props) {
super(props);
this.state = { tasks: [] };
this.grabTasks = this.grabTasks.bind(this);
this.handleDelete = this.handleDelete.bind(this);
}
// Grabs the list of tasks from the firebase database
// and then sets the state to x.
grabTasks() {
var x = [];
db.ref('tasks').on('value', function(snapshot) {
return x = snapshot.val();
});
this.setState({ tasks : x });
}
// In charge of removing the task items when they are clicked.
// This function is passed to TaskItems via props
handleDelete(taskToDelete) {
var newTasks = _.reject(this.state.tasks, function(task) {
return task == taskToDelete
});
this.setState({tasks: newTasks});
}
render() {
return (
<div id="wrapper">
<div id="navigation">
<Navbar />
</div>
<div id="content">
<div className="container">
<div className="row">
<h2>Tasks</h2>
<div onClick={this.grabTasks} className="btn">Get Tasks</div>
<TaskItems tasks={this.state.tasks} handleDelete={this.handleDelete} />
</div>
</div>
</div>
</div>
)
}
}
TaskItems.js
// TaskItems Child Component
const TaskItems = (props) => {
var hello = props.tasks.map((task,index) => {
return(
<li className="collection-item" key={index}>
{task}
<a onClick={props.handleDelete.bind(this, task)}>
<i className="fa fa-times-circle remove-task" aria-hidden="true"></i>
</a>
</li>
);
});
return (
<div>
<ul className="collection">
{hello}
</ul>
</div>
);
}
export default TaskItems
最佳答案
您的 db.ref('tasks')
是一个异步方法。你不应该认为它是同步的。试试这个:
grabTasks() {
var that = this;
db.ref('tasks').on('value', function(snapshot) {
var x = snapshop.val();
that.setState({tasks : x})
});
}
在加载屏幕时获取这些任务:
componentDidMount(){
this.grabTasks();
}
关于javascript - React Array Map 与 Firebase 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312796/