I have a reactjs application. In this I want to manage a list from parent component. This application can add a object to list, delete it from list and show added objects in a table.
My problem is that I can add an object, but must refresh the whole page that it is shown in the list. The two way binding not work and I don't know how to implement it. I hope you can help me.
class Wrap extends React.Component{
constructor(){
super();
this.state = {
player: []
};
}
render(){
return(
<div id ="wrapperComponent">
<Table/>
<Create />
</div>
);
}
}
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
player: []
};
this.deletePlayer = this.deletePlayer.bind(this);
}
componentDidMount() {
axios.get('http://localhost:8081/player')
.then(res => {
this.setState({ player: res.data });
console.log(this.state.player);
});
}
deletePlayer(id) {
fetch(`http://localhost:8081/player/${id}`, {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(() => {
let updatedPlayers = [...this.state.player].filter(i => i.id !== id);
this.setState({player: updatedPlayers});
});
}
class Create extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
ownerid: ''
};
}
onChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}
onSubmit = (e) => {
e.preventDefault();
const { name, ownerid} = this.state;
axios.post('http://localhost:8081/player', { name, ownerid})
.then(() => this.setState(() => ({
})))
}
```
Add your .get call in a method in parent component and pass it as props. Use it to refresh your list.
class Wrap extends React.Component {
constructor() {
super();
this.state = {
players: []
};
}
getData = () => {
axios.get('http://localhost:8081/player')
.then(res => {
this.setState({ players: res.data });
});
}
removePlayerFromState = (id) => {
let updatedPlayers = [...this.state.players].filter(i => i.id !== id);
this.setState({players: updatedPlayers});
}
render() {
return (
<div id="wrapperComponent">
<Table getData={this.getData} players={this.state.players} removePlayerFromState={this.removePlayerFromState}/>
<Create getData={this.getData}/>
</div>
);
}
}
class Table extends React.Component {
// use this.props.players
}
class Create extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
ownerid: ''
};
}
onChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}
onSubmit = (e) => {
e.preventDefault();
const { name, ownerid } = this.state;
axios.post('http://localhost:8081/player', { name, ownerid })
.then(() => this.props.getData())
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.