我試圖用React和React路由器構建一個示例CRUD應用程序,並且我無法弄清楚爲什麼狀態不會傳遞到子組件中期待它。當我點擊edit
路由時,它呈現Edit
組件,它從數據庫中抓取我想要的小貓,並將它的信息發送到Form組件,該組件用於編輯現有的小貓或添加一個新的小貓。將狀態傳遞給兒童組件作爲道具不工作
下面是編輯組件:
import React, { Component } from 'react';
import axios from 'axios';
import { match } from 'react-router-dom';
import Form from './Form';
export default class Edit extends Component {
constructor(props) {
super(props)
this.state = {}
}
componentDidMount() {
axios.get(`/updateKitten/${this.props.match.params.id}`)
.then(res => {
const kitten = res.data
this.setState({ kitten })
console.log(this.state.kitten.name) //Sammy, or something
})
.catch(err => console.log(err))
}
render() {
return (
<Form
name={this.state.kitten.name} // throws error or undefined
description={this.state.kitten.description} //throws error or undefined
route={this.props.match.params.id}
/>
)
}
}
編輯組件通過名稱,描述和路線這個表單組件:
import React, { Component } from 'react';
import axios from 'axios';
export default class Add extends Component {
constructor(props) {
super(props)
this.state = { name: this.props.name, description: this.props.description}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
const name = e.target.name;
const value = e.target.value;
this.setState({
[name]: value
});
}
handleSubmit(e) {
axios.post(`/addKitten/${this.props.route}`, this.state)
.then(this.setState({ name: '', description: '' }))
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>Name</label>
<input type='text' name="name" value={this.state.name}
onChange={this.handleChange}/>
<label>Description</label>
<input type='text' name="description" value={this.state.description}
onChange={this.handleChange}/>
<input type='submit' value='Submit' />
</form>
)
}
}
而且我得到以下錯誤:
bundle.js:28950 Uncaught TypeError: Cannot read property 'name' of undefined
試圖發送該信息爲pr選擇Form
組件。
我在做什麼錯?