我有一个if-else情况,在其他情况下我试图从Component加载数据以及将数据传递给它。 这个代码是这样的
import React from 'react';
import ReactDom from 'react-dom' ;
//import data from '../data.json';
import { withRouter, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js'
class Author extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
load:false,
content:'',
}
this.loadBlog=this.loadBlog.bind(this);
}
loadBlog(i){
that.setState({
load:true,
})
// this.props.router.history.push('/fullblog');
//window.location='/fullblog'+this.state.data;
browserHistory.push('/fullblog')
}
render(){
if(this.state.load===false){
return(
<div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
)
}//else{
// //return(<div><FullBlog data={this.state.data}/></div>)
// }
}
}
The function is loadBlog in which I tried to use browserHistory.push() but I don't know how can I pass data into the same and also I get error `'Cannot read property push of undefined.'`
然后,我尝试使用像这样的链接标签
if(this.state.load===false){
return(
<Link to={'/fullblog'+this.props.data}><div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
</Link>
)
}//else{
// //return(<div><FullBlog data={this.state.data}/></div>)
// }
}
}
对于上述情况,我收到错误invalid react element
。
实现相同的正确方法是什么。我正在使用react-router v4。
编辑:
将代码更新为
<div>
<Link to={'/fullblog/${this.props.data}'}/><div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
</div>
我得到了上面的Invariant违规错误和React元素错误。
答案 0 :(得分:1)
你也应该在else部分返回一些东西。取消注释,来自else块的代码。
答案 1 :(得分:1)
您正在返回undefined。您始终需要在render
方法中返回React组件。您可以做的是以下内容,因为这是一种常见的模式:
render(){
let content = (
<p>I'm returning this by default</p>
);
if (this.state.load===false) {
content = (
<div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
);
}
return content;
}