Reactjs 基于id查找对象,然后在react组件中呈现该对象的可能性
我想根据对象的Reactjs 基于id查找对象,然后在react组件中呈现该对象的可能性,reactjs,Reactjs,我想根据对象的id查找对象,然后在组件中渲染它 getInitialState() { return { item: [] } }, componentDidMount() { this.setState({item: this.props.items.filter(item => (item.id == this.props.match.params.id))}) } componentDidUpdate() { console.log(this.state.item)
id
查找对象,然后在组件中渲染它
getInitialState() {
return { item: [] }
},
componentDidMount() {
this.setState({item: this.props.items.filter(item => (item.id == this.props.match.params.id))})
}
componentDidUpdate() {
console.log(this.state.item) // result is empty array
}
如果我不想使用setState
并在render
方法中查找对象,那么我将得到:
render() {
var item = this.props.items.find(item => (item.id == this.props.match.params.id))
console.log(item) // First it is undefined then it will be found
var title = item.title
return (
<div>
{title}
</div>
render(){
var item=this.props.items.find(item=>(item.id==this.props.match.params.id))
console.log(item)//首先它是未定义的,然后会被找到
var title=item.title
返回(
{title}
如何根据params.id
查找对象,然后在组件内部渲染它?render(){
render() {
var item = this.props.items.find(item => (item.id == this.props.match.params.id))
//This is what you should do to show that it's loading.
if(!item || !item.id){
return <div>Loading</div>
}
console.log(item) // First it is undefined then it will be found
var title = item.title
return (
<div>
{title}
</div>
var item=this.props.items.find(item=>(item.id==this.props.match.params.id))
//这是您应该做的,以显示它正在加载。
如果(!item | |!item.id){
回装
}
console.log(item)//首先它是未定义的,然后会被找到
var title=item.title
返回(
{title}