您好我需要帮助反应渲染。当我第一次去/ role时,const roleLength = this.props.roles.length> 0;仍然是定义。但是当我在提交给/ role之后创建并重新路由到/ addRole时,Uncaught ReferenceError:roleLength未在Role.render中定义
import { getRoles } from '../../actions/roleActions'
import { refreshToken } from '../../actions/authActions'
import { connect } from 'react-redux'
import _ from 'lodash'
import { Link } from "react-router"
class Role extends React.Component {
constructor(props) {
super(props);
this.state = {
roles: []
};
}
componentWillMount(){
this.props.getRoles().then(() => {
console.log('this role props: ', this.props)
if(this.props.errors.code === 'UNAUTHORIZED'){
this.props.refreshToken().then(() => {
this.props.getRoles()
})
}
})
}
render(){
const roleArr = _.valuesIn(this.props.roles)
const roleLength = this.props.roles.length > 0;
return (
<div>
<Link className="add-btn btn btn-success" to="/addRole" ><i className="fa fa-plus"></i>Add Role</Link>
<h1>Roles</h1>
<table className="table table-responsive table-bordered">
<thead>
<tr>
<td>Name</td>
<td>Created At</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{ roleLength ? (
roleArr.map((roles, i) => {
return (
<tr key={i}>
<td>{roles.name}</td>
<td>{roles.createdAt}</td>
<td>
<Link className="btn btn-sm btn-warning" >
<i className="fa fa-pencil"></i>
</Link>
<button className="btn btn-sm btn-danger">
<i className="fa fa-trash-o"></i>
</button>
</td>
</tr>
);
})) : (<tr>No Roles Found</tr>)
}
</tbody>
</table>
</div>
);
}
}
Role.propTypes = {
getRoles: React.PropTypes.func.isRequired,
errors: React.PropTypes.object.isRequired,
refreshToken: React.PropTypes.func
}
Role.contextTypes = {
router: React.PropTypes.object.isRequired
}
function mapStateToProps(state) {
return{
roles: state.roleReducer.roles,
links: state.roleReducer.links,
errors: state.roleReducer.errors
}
}
export default connect(mapStateToProps, { getRoles, refreshToken })(Role)
这是我的添加角色代码:
this.props.postRole(this.state).then(() => {
if(this.props.errors.message){
this.setState({errors: this.props.errors, isLoading: false});
}else{
this.context.router.push('/roles')
}
}
);
我想知道这是否与componentWillMount()有关 您的建议和答案非常感谢。谢谢
PS:数据是通过
创建的答案 0 :(得分:1)
可能会出现错误,因为this.props.roles
本身可能未定义。试试这个
render(){
const roleArr = _.valuesIn(this.props.roles)
return (
<div>
<Link className="add-btn btn btn-success" to="/addRole" ><i className="fa fa-plus"></i>Add Role</Link>
<h1>Roles</h1>
<table className="table table-responsive table-bordered">
<thead>
<tr>
<td>Name</td>
<td>Created At</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{ this.props.roles ? (
roleArr.map((roles, i) => {
return (
<tr key={i}>
<td>{roles.name}</td>
<td>{roles.createdAt}</td>
<td>
<Link className="btn btn-sm btn-warning" >
<i className="fa fa-pencil"></i>
</Link>
<button className="btn btn-sm btn-danger">
<i className="fa fa-trash-o"></i>
</button>
</td>
</tr>
);
})) : (<tr>No Roles Found</tr>)
}
</tbody>
</table>
</div>
);
}
}