【发布时间】:2020-10-14 23:16:44
【问题描述】:
我是 React 新手,在将 props 传递给 API URL 方面需要帮助。我有两个类组件-> (MyClass) 工作正常。但是,当我在其他类组件(MyOtherClass)中使用来自 MyClass 的变量作为道具时,它似乎只在“渲染”部分起作用。我的意思是<div> variable: {variable}, url : {url2}</div> 按预期显示在应用程序中,但是当我尝试将此变量从道具传递到 API URL 时,它不起作用,而是 URL 看起来像这样:"http://localhost:55111/status/[object Object]"。有什么想法可能导致问题吗??
这是我的代码:
import React, { Component } from 'react'
import axios from 'axios'
export default class MyClass extends Component {
constructor(props) {
super(props);
this.state = {
data: {}
}
}
componentDidMount() {
axios
.get("http://localhost:55111/start")
.then(response => {
this.setState({
data: response.data
});
console.log(this.state.data);
})
.catch(err => {
this.err = err;
});
}
render() {
const variable = this.state.data.sent
return (
<div>
<h1>Hello worlds</h1>
<p>var: {variable}</p>
<MyOtherClass variable={variable} />
</div>
);
}
}
这是另一个导致麻烦的类组件:
class MyOtherClass extends Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
async componentDidMount() {
const {variable} = this.props
axios.get(`http://localhost:55111/status/${variable}`)
.then(response => {
this.setState({
data: response
});
console.log(this.state);
})
render() {
const { variable } = this.props
const url2 = `http://localhost:55111/status/${variable}`
return (
<div>variable: {variable}, url : {url2}</div>
);
}
}
【问题讨论】:
标签: reactjs rest react-props