Javascript 如何在react+;消防商店?
我正在学习react而不使用redux、mobx或任何其他库。 我不使用redux等的原因是有人告诉我,在使用库之前使用反应是很重要的。 我试图从firestore获取数据并进行渲染,但由于异步,我一直坚持渲染数据。 我无法渲染,因为渲染时我没有获取数据 我的react版本是16,我使用firestore练习react。 这是我的密码 不管你给我什么建议,我都会感激你的。 多谢各位Javascript 如何在react+;消防商店?,javascript,reactjs,google-cloud-firestore,Javascript,Reactjs,Google Cloud Firestore,我正在学习react而不使用redux、mobx或任何其他库。 我不使用redux等的原因是有人告诉我,在使用库之前使用反应是很重要的。 我试图从firestore获取数据并进行渲染,但由于异步,我一直坚持渲染数据。 我无法渲染,因为渲染时我没有获取数据 我的react版本是16,我使用firestore练习react。 这是我的密码 不管你给我什么建议,我都会感激你的。 多谢各位 categoryButtonStart.js 从“React”导入React; 从“./CategoryBut
categoryButtonStart.js
从“React”导入React;
从“./CategoryButton”导入CategoryButton;
从“../shared/Firebase”导入{test};
导出默认类CategoryButton.Component{
类别=[];
componentDidMount(){
test()。然后((querySnapshot)=>{
querySnapshot.forEach((doc)=>{
this.categories.push(doc.id).bind(this);
});
});
}
render(){
if(this.categories.length!==0){
console.log(this.categories);
返回(
此块用于类别按钮集。
{
this.categories.map(category=>)
}
);
}否则{
返回装载。。。;
}
}
}
CategoryButton.js
从“React”导入React;
导出默认值(道具)=>{
返回(
这是分类按钮。
{props.name}
);
}
您正在检索数据,但没有设置您的状态,您根本没有任何状态。这就是为什么组件在获取数据后不会重新渲染的原因。也许有一种方法是这样的(可能有更好的方法):
导出默认类categoryButton.Component{
状态={
类别:[],
};
componentDidMount(){
测试()
.then(querySnapshot=>querySnapshot.map(doc=>doc.id))
.then(data=>this.setState({categories:data}));
}
render(){
if(this.state.categories.length){
log(this.state.categories);
返回(
此块用于类别按钮集。
{
this.state.categories.map(category=>)
}
);
}否则{
返回装载。。。;
}
}
}
请查看Firestorter,如果它正是为了这个目的而存在的,您不需要创建redux存储或其他任何东西
哦,我认为使用“状态”是redux的一种方式,但我认为是另一种方式。谢谢,我会试试看,然后再仔细看一下React文档:)“状态”在React中占有很大的位置。
import React from 'react';
import CategoryButton from './CategoryButton';
import {test} from '../shared/Firebase';
export default class CategoryButtonSet extends React.Component {
categories = [];
componentDidMount() {
test().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.categories.push(doc.id).bind(this);
});
});
}
render() {
if(this.categories.length !== 0) {
console.log(this.categories);
return (
<div className="category-block">
This block is for the category button set.
{
this.categories.map(category => <CategoryButton key={category} name={category}/>)
}
</div>
);
} else {
return <div>Loading...</div>;
}
}
}
import React from 'react';
export default (props) => {
return (
<div className="category-block__button">
Here's the category button.
<button>{props.name}</button>
</div>
);
}
export default class CategoryButtonSet extends React.Component {
state = {
categories: [],
};
componentDidMount() {
test()
.then( querySnapshot => querySnapshot.map( doc => doc.id ) )
.then( data => this.setState( { categories: data } ));
}
render() {
if(this.state.categories.length) {
console.log(this.state.categories);
return (
<div className="category-block">
This block is for the category button set.
{
this.state.categories.map(category => <CategoryButton key={category} name={category}/>)
}
</div>
);
} else {
return <div>Loading...</div>;
}
}
}