我是 react 新手,无法弄清楚如何将从服务器接收到的数据从父组件传递到子组件,如下所示:
//parent component
class AlumniComponent extends React.Component {
state = {
profile : {},
error: false
}
componentDidMount(){
Axios.get('https://jsonplaceholder.typicode.com/users/1')
.then(response=>{
// console.log(response.data);
this.setState({profile: response.data})
})
.catch(error=>{
console.log(error);
this.setState({error: true})
})
}
render() {
const profile = this.state.profile;
return(
<AboutComponent data={profile} tab="about"/>
);
}
在我的子组件中:
class AboutComponent extends React.Component {
constructor(props){
super(props);
this.state = {
data: {
name: props.data // <--- the props are coming coming from the parent component !?
},
selectedOption: null,
};
}
render (){
return (
<Form.Control type="text" value={JSON.stringify(this.state.data)} disabled />
);
}
输入值作为空对象出现:{"name":{}}
最佳答案
我会尽量避免存储 props
state
里面这样你的parent
和children
组件不会失去同步。相反,请使用 props
中您需要的内容。 children
里面然后如果你需要根据 props
存储一些其他信息通过的,使用 state
为了那个原因。
这是一个例子:
class AlumniComponent extends React.Component {
state = {
profile: {},
isLoading: true,
error: false
};
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(res => res.json())
.then(data => {
this.setState({
profile: data,
isLoading: false
});
})
.catch(error => {
this.setState({
error: error.message,
isLoading: false
});
});
}
render() {
const { profile, isLoading, error } = this.state;
if (isLoading) {
return `Loading`;
}
if (!isLoading && error) {
return `Something went wrong`;
}
return <AboutComponent data={profile} />;
}
}
class AboutComponent extends React.Component {
constructor(props) {
super(props);
const initialState = {
name: this.props.data.name,
selectedOption: null
}
this.state = { ...initialState }
}
handleChange = event => {
this.setState({
name: event.target.value
});
};
render() {
const { name } = this.state;
return <input type="text" value={name} onChange={this.handleChange} />;
}
}
function App() {
return (
<div className="App">
<AlumniComponent />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
另外,我不知道 <Form.Control />
是什么?组件期望 value
属性,但请确保获取所需的正确信息,而不是将整个 Prop /对象传递给其中。
class AboutComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
name: this.props.data.name
}
}
handleChange = (event) => {
this.setState({
name: event.target.name
})
}
render() {
return (
<Form.Control
type="text"
value={this.state.name}
onChange={this.handleChange}
disabled
/>
)
}
}
关于javascript - 在基于 react 类的组件中将 Prop 从父级传递给子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60532705/