我正在尝试进行条件渲染,以在React应用程序中显示“编辑”和“删除”按钮。
<div>
{author_id === user_id &&
<Container>
<Row xs="2">
<Col><Button color="primary" size="sm">Edit</Button></Col>
<Col><Button color="danger" size="sm">Delete</Button></Col>
</Row>
</Container>
}}
</div>
我得到'author_id' is not defined
和'user_id' is not defined
是因为album_id
从componentDidMount()
中的数据库中获取数据,而user_id
从Context.Provider中获取数据。来自另一个组件。
componentDidMount() {
const { match: { params} } = this.props;
console.log('COMPONENT HAS MOUNTED');
fetch(`http://localhost:8000/albums/${params.albumId}`)
.then((response) =>
response.json())
.then((data) => {
this.setState({ albums : data });
}).catch((error) => {
console.log("Error " + error)
})
}
render() {
if(this.state.albums[0]){
let author_id = this.state.albums[0].author;
}
if(this.context.user){
let user_id = this.context.user.sub;
}
Album.contextType = Auth0Context;
既然这两个变量没有立即值,那我该怎么做才能使代码工作呢?
答案 0 :(得分:1)
您需要检查user_id
和author_id
是否正确,然后检查它们是否相同,然后然后呈现按钮。
这样的事情应该做你想要的:
render() {
const user_id = this.context.user ? this.context.user.sub : null;
const author_id = this.state.albums[0] ? this.state.albums[0].author : null;
const shouldRenderButton = user_id && author_id && user_id === author_id;
return (
...
{ shouldRenderButton && <div>...</div> }
...
)
}
答案 1 :(得分:0)
使用JavaScript进行救援。使用NaN
作为默认值。与每个数字相比,比较返回false
。将NaN
与NaN
进行比较也是错误的。
NaN == 128; // false
NaN == 'mau'; // false
NaN == NaN; // false
因此,即使您拥有一个值(例如user_id
)而没有另一个值,它仍然会导致false,因此不会呈现您的代码段。
但是正如JMadelaine所提到的,如果您还没有任何数据(或渲染一个Loading-Icon),最好根本不渲染任何东西。
render() {
if(!this.state.albums.length) {
return <span>Loading</span>
}
//.. other rendering
return <div>{/*...*/}</div>
}
这应该可以解决问题。