【发布时间】:2018-06-22 13:14:21
【问题描述】:
我有一个使用 Redux 和 React 构建的 React 应用程序,并且我正在使用 JSON 获取数据。由于 React 是一个生命周期,如果数据库中的内容发生更改,react 是否应该自动更新获取的数据而不刷新?
我尝试过使用componentWillReceiveProps,但这不起作用
src/components/layout.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import { fetchUsers, postUsers, deleteUsers } from '../actions/usersAction';
import './css/styles.css';
class Layout extends Component {
constructor(props){
super(props);
this.state = {
id: '',
name: '',
age: ''}
}
onUserUpdate(filed, event){
if (filed === 'name') {
this.setState({
name: event.target.value
});
}
if (filed ==='age') {
this.setState({
age: event.target.value
});
}
}
handlePostUsers(e){
e.preventDefault();
this.props.postUsers(this.state.name,this.state.age);
}
componentDidMount() {
this.props.fetchUsers();
}
componentWillReceiveProps(nextProps) {
const nameChanged = nextProps.users !== this.props.users;
if (nameChanged) {
this.props.fetchUsers(nextProps)
}
console.log('here is componentWillReceiveProps',nextProps)
}
render() {
const { act } = this.props;
const fetchUserss = act.users.map(d => <tr key={d.id}><td>{d.id}</td><td>{d.name}</td><td>{d.age}</td><td><button onClick={this.props.deleteUsers.bind(this)}>Delete</button></td></tr>);
return (
<div className="App">
<label>
name:
</label>
<input type="text" name="name" onChange={this.onUserUpdate.bind(this, 'name')} placeholder="Enter Name"/>
<label>
age:
</label>
<input type="text" name="age" onChange={this.onUserUpdate.bind(this, 'age')} placeholder="enter username"/>
<button onClick={(e) => this.handlePostUsers(e)}>Add News</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody>
{fetchUserss}
</tbody>
</table>
</div>
);
}
}
function mapStateToProps(state) {
return {
act: state.users,
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({fetchUsers, postUsers, deleteUsers}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(Layout);
如果我错过任何信息,请告诉我。
如果已经有人问过这个问题,如果您能指出我正确的方向,我将不胜感激。
非常感谢!
【问题讨论】:
标签: javascript reactjs redux react-redux