3 回答

TA貢獻1808條經驗 獲得超4個贊
您并沒有真正設置狀態,或者我還沒有看到那種語法。
通常,我會做類似...
this.setState({ stateProp: valueToAssign });
所以,在你的情況下......
this.setState({ d: res.data });
我認為您缺少帶類的構造函數。例如來自反應站點。
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
所以在你的情況下......
constructor(props) {
super(props);
this.state = { d: [] };
}
為了確保我分配了正確的值,我會做一個“console.log(res.data)”來檢查。

TA貢獻1875條經驗 獲得超5個贊
它確實取決于 API 響應的格式。您不能像這樣渲染對象或數組:
render() {
const object = {foo: 'bar'};
return (
<div>
{object}
</div>
}
但是你可以像這樣渲染它:
render() {
const object = {foo: 'bar'};
return (
<div>
{object.foo}
</div>
}

TA貢獻1790條經驗 獲得超9個贊
import axios from 'axios';
export default class PersonList extends React.Component {
constructor(props) {
super(props);
this.state = { key: []};
}
componentDidMount() {
axios.get(`http://localhost:8080/login/?username=abc&password=welcome1`)
.then(res => {
this.setState(key: res.data);
})
}
render() {
return (
<ul>
{ this.state.key}
</ul>
)
}
}
添加回答
舉報