我正在学习在我的react应用程序中实现未声明的。
我做了一个简单的应用程序,使用Unstated显示一个Note。
这是我的NoteContainer:
class NoteContainer extends Container {
state = {
title: 'My Note',
desc: 'This note state is managed with unstated',
isDisplaying: false,
}
constructor() {
super()
this.show = this.show.bind(this);
}
show() {
this.setState({ isDisplaying: !this.state.isDisplaying })
console.log(this.state);
}
}如您所见,非常简单,它只需更改状态中的isDisplaying属性,这样我就可以在Note.js组件上使用它来显示注释的标题和消息,如下所示:
class Note extends Component {
state = {
isShowing: false,
}
render() {
if (this.state.isShowing) {
return (
<Subscribe to={[NoteContainer]}>
{noteContainer => (
<div className="container">
<p>{noteContainer.state.title}</p>
<p>{noteContainer.state.desc}</p>
</div>
)}
</Subscribe>
)
}
return (
<Subscribe to={[NoteContainer]}>
{noteContainer => (
<div className="container">
<button className="btn btn-success" onClick={() => {
noteContainer.show();
this.setState({
isShowing: noteContainer.state.isDisplaying,
})
console.log(this.state);
}}>
See Note!
</button>
</div>
)}
</Subscribe>
)
}
}所需的功能是当我点击See Note!按钮时,它会在按钮上方显示注释的标题和说明,如果我再次单击它,它会隐藏它们。
但是,我得到的是它创建了另一个Subscribe组件,这似乎删除了"See Note!“按钮部分。这是结果的图像。

问题是我不能再次使用按钮来隐藏备注信息,我显然是错误地使用了subscribe组件,但我不能想出另一种方式来使用条件使用unstated,所以在这方面的任何帮助都将不胜感激。
提前感谢,祝你一周愉快!
发布于 2019-02-04 23:47:06
我已经设法用内联if条件函数解决了这个问题。然而,我对这个解决方案感到不舒服,我想知道如何实现一个完整的if条件,所以如果有人知道请留下评论!
render() {
return (
<Subscribe to={[NoteContainer]}>
{noteContainer => (
<div className="container">
<p>{noteContainer.state.isDisplaying ? noteContainer.state.title : ''}</p>
<p>{noteContainer.state.isDisplaying ? noteContainer.state.desc : ''}</p>
<button className="btn btn-success" onClick={() => {
noteContainer.show();
}}>
See Note!
</button>
</div>
)}
</Subscribe>
)
}发布于 2019-02-04 22:59:59
这是一个反模式:
this.setState({ isDisplaying: !this.state.isDisplaying })先勾选,然后设置状态:
let answer = this.state.isDisplaying ? true : false
this.setState({isDisplaying: answer})或者使用prevState变量
this.setState((prevState, props) => ({
isDisplaying: prevState.isDisplaying ? true : false
}));https://stackoverflow.com/questions/54518576
复制相似问题