【发布时间】:2020-05-17 04:12:15
【问题描述】:
我正在尝试获取 json 对象的列表,例如:
[ {yes: 1, no: 0, nil: 0},
{yes: 0, no: 1, nil: 0},
{yes: 1, no: 0, nil: 0},
{yes: 0, no: 1, nil: 0}].
然而,目前,一旦我点击上面的任何一个,它就会保持为 1,最终全部变为 1,这不是我想要的:
[ {yes: 1, no: 0, nil: 0},
{yes: 1, no: 1, nil: 0},
{yes: 1, no: 1, nil:0 },
{yes: 1, no: 1, nil: 1}]
对于每次点击,我想将状态推送到 firebase 数据库,然后从应用程序中将其作为 json 对象检索以绘制图表。
export default class Vote extends Component {
constructor(props) {
super(props)
this.state = {
yes: 0,
no: 0,
nil: 0,
};
this.current = [];
};
handleClick = (e) => {
const ref = baseDb
.ref("votes")
ref.push({
dataset: this.state
})
this.setState({[e.target.name]: 1 })
this.current.push(this.state)
console.log(this.current)
}
<div className="form-group row">
<div>
<button className="btn btn-primary" onClick={this.handleClick}
name= "yes"
>
Yes
</button>
</div>
<div>
<button className="btn btn-primary" onClick={this.handleClick}
name= "no"
>
NO
</button>
</div>
<div>
<button className="btn btn-primary" onClick={this.handleClick}
name= "nil"
>
Undecided
</button>
</div>
</div>
【问题讨论】:
-
你可以使用
this.setState(<initial state>) -
这个我试过了,没用!
-
这段代码有什么问题?你的用户界面没有更新吗?还是数据库中的数据不是你所期望的?
-
它的用户界面。对于每次点击,我希望所有状态值都回到 0,但它会保持为 1。
-
你能澄清一下你想在问题中发生什么吗?您想在点击时更新 Firestore,但在点击时重置状态?这有点难以理解,如果你用一个你想要发生的例子来澄清和更新你的问题,它会更容易帮助你。
标签: javascript reactjs firebase express react-redux