gpt4 book ai didi

javascript - React、ES6+7 ajax 调用不起作用?

转载 作者:行者123 更新时间:2023-12-03 07:44:54 27 4
gpt4 key购买 nike

从昨天开始我就一直对此感到困惑。我似乎无法使用 ES6+7 语法将本地服务器通过 json-server 的数据渲染到我的 React 代码中。我也尝试过使用 ES5 方式,但没有得到任何结果。

App.js

import React, {Component} from 'react';
import {render} from 'react-dom';

const source = "http://localhost:3000/";

class App extends Component {

state = { authors: [] };

static defaultProps = {
source: ''
};

static propTypes() {
source: React.PropTypes.string
};

loadAuthors() {
fetch(source)
.then(response => response.json())
.then(data => this.setState({ authors: data }))
.catch(err => console.error(source, err.toString()))
}

componentDidMount() {
this.loadAuthors()
}

render() {
const renderData = this.state.authors.map(function(author) {
return (
<div>
<p>author.id</p>
<p>author.firstName</p>
<p>author.lastName</p>
</div>
)
});
return (
<div>
<h1>
Welcome to the react starter!
</h1>
<h1>
{renderData}
</h1>
</div>
);
}
}

render(<App />, document.getElementById('root'));

JSON 源

{
authors: [
{
id: "zarghon-shah",
firstName: "Zarghon",
lastName: "Shah"
},
{
id: "khpalwalk-pashtun",
firstName: "Khpalwalk",
lastName: "Pashtun"
},
{
id: "sazinda-khudai",
firstName: "Sazinda",
lastName: "Khudai"
}
]
}

提前致谢

最佳答案

看起来您需要将 JSX 大括号放在对“author”的引用周围,以便插值正确发生:

const renderData = this.state.authors.map(function(author) {
return (
<div>
<p>{author.id}</p>
<p>{author.firstName}</p>
<p>{author.lastName}</p>
</div>
)
});

否则你只是写出文字字符串“author.id”等。

关于javascript - React、ES6+7 ajax 调用不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35249554/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com