我有一个表格,其中显示了数据列表。单击行时,我想将用户导航到下一页。 以下是我的代码:
export default class Venues extends Component {
constructor(props) {
super(props);
this.state = {
venues: [],
isLoading: false,
}
}
componentDidMount() {
this.setState({isLoading:true});
this.getVenueList();
}
getVenueList() {
ApiService.getData(apiConfig.GET_VENUES, {
}).then((res) => {
if (res.data && res.data.error == null) {
console.log(res.data);
this.setState({ venues: res.data.result, isLoading: false });
console.log(this.state.venues);
console.log("venues");
} else {
alert(res.data.error.description );
}
});
}
handleRowClick() {
this.props.history.push('/projectList');
}
addVenue() {
this.props.history.push('/add_venue');
}
render() {
return (
<div className="col-md-6 offset-md-3">
<Form onSubmit={this.onSubmit}>
<div className="form-group">
<div style={divStyle}>
<Typography variant="h4" style={style}>Venues</Typography>
<div style={{
display: 'flex',
justifyContent: 'flex-end',
marginRight: '20px'
}}>
<Button color="primary" onClick={() => this.addVenue()}>
Add Venue
</Button></div>
{this.state.isLoading ? (<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh'
}}><div className="spinner-border text-primary" role="status" >
<span className="sr-only">Loading...</span>
</div></div>) : (
<Table>
<TableHead>
<TableRow>
<TableCell>S.No.</TableCell>
<TableCell align="center">Venue Name</TableCell>
<TableCell align="center">Role</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.venues.map(row => (
<TableRow key={row.id} onClick={this.handleRowClick}>
<TableCell component="th" scope="row">
{this.state.venues.indexOf(row) + 1}
</TableCell>
<TableCell align="center">{row.venueName}</TableCell>
<TableCell align="center">{row.venueAddress}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
</div>
</Form>
</div>
);
}
}
点击行时出现以下错误:
TypeError: Cannot read property 'props' of undefined I am getting this error on handleRowClick() function.
有人可以帮我解决这个问题吗?
最佳答案
您需要将处理程序绑定(bind)到类实例范围。
选项 1: 像使用箭头语法一样声明函数,因为箭头函数中 this 的值总是从封闭范围继承。
https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/
handleRowClick = () => {
this.props.history.push('/projectList');
}
选项 2 在构造函数中显式绑定(bind)处理函数的范围。
constructor(props) {
super(props);
this.state = {
venues: [],
isLoading: false,
}
this.handleRowClick = this.handleRowClick.bind(this);
}
关于reactjs - 在 React JS 中导航到表行上的下一页单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64554113/