Javascript 将Fetch与ReactJS一起使用
我对ReactJS非常陌生,所以这是我在其中使用Fetch的实现Javascript 将Fetch与ReactJS一起使用,javascript,reactjs,Javascript,Reactjs,我对ReactJS非常陌生,所以这是我在其中使用Fetch的实现 class App extends React.Component { function postData(url, data) { // Default options are marked with * return fetch(url, { body: JSON.stringify(data), // must match 'Content-Type' header
class App extends React.Component {
function postData(url, data) {
// Default options are marked with *
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // parses response to JSON
}
render() {
const test_content = ["first", "second", "third"];
const initial_data = {
'id': 1,
'model-name': 'Joke'
};
postData('/start-jokes/', initial_data)
.then(data => console.log(data)
) // JSON from `response.json()` call
.catch(error => console.error(error));
const jokes_div = test_content.map((item, i) => (
<div key={i} className="card col-md-7">
<div className="card-body">
{item}
</div>
</div>
));
return <div className="container" id="jokes">{jokes_div}</div>;
}
}
// ========================================
ReactDOM.render(
<App />,
document.getElementById('root')
);
笑话数组在一个对象中有一个id和文本,该文本将与test\u content
相同,用于用它自己的唯一键id
填充项目,如图所示
任何关于现在如何从那里填充的提示都将非常受欢迎。由于您是异步的,您需要考虑生命周期:
。然后(response=>response.json())
将结果设置为状态,例如。然后(response=>this.setState({crooks:response.json()}))
(this.state.jones | | |[])而不是测试内容
在更大的应用程序中,我会考虑分离渲染和数据管理(即做两个组件),但是我希望你在上面的几点上还有一步……/p>< p>永远不要在渲染中调用API。如果希望在页面呈现时加载数据,请调用componentDidMount中的函数;否则,如果您想加载一些其他事件或输入更改,请在onChange事件中调用它,如前所述,无需返回结果,您可以设置state响应
Object { status: "ok", jokes: Array[10], ref-id: 11 }
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data : [],
}
}
componentDidMount(){
this.postdata()
}
postdata(){
var self = this;
fetch(url, {
body: JSON.stringify(data),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(response => response.json()).then((json) => {
self.setState({ data : json.data }) // which ever the key hold the data
})
}
render(){
return(
<div>
{this.state.data.length == 0 &&
<div> No options available.</div>
}
{this.state.data.length > 0 &&
<div className="container" id="jokes">
{this.state.data.map(function(item,i){
return(
<div key={i} className="card col-md-7">
<div className="card-body">
{item} // here you are getting object in item. Get the key from the object like item.name
</div>
</div>
)
})}
</div>
}
</div>
)
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
this.state={
数据:[],
}
}
componentDidMount(){
这是postdata()
}
postdata(){
var self=这个;
获取(url{
正文:JSON.stringify(数据),
缓存:“无缓存”,
凭据:“相同来源”,
标题:{
“用户代理”:“Mozilla/4.0 MDN示例”,
“内容类型”:“应用程序/json”
},
方法:“POST”,
模式:“cors”,
重定向:“跟随”,
推荐人:“无推荐人”,
})
。然后(response=>response.json())。然后((json)=>{
self.setState({data:json.data})//哪个键保存数据
})
}
render(){
报税表(
{this.state.data.length==0&&
没有可用的选项。
}
{this.state.data.length>0&&
{this.state.data.map(函数(项,i){
返回(
{item}//这里是在item中获取对象。从类似item.name的对象中获取密钥
)
})}
}
)
}
}
以这种方式尝试,但发现了一个有趣的错误,不确定是否是因为我使用了setState。代码现在看起来像这样,它抛出以下错误SyntaxError:http://35.196.142.180/static/js/react-script.js: 意外标记(7:23)5 |数据:[],6 |}>7 | componentDidMount(){^8 | this.postdata()9 |}10 |
@SamuelM。现在请检查,我已经更新了代码。忘记关闭构造函数的括号,或者必须指出另一个bugSyntaxError:http://35.196.142.180/static/js/react-script.js: 意外标记(34:17)32 | render(){33 | return(>34 |{this.state.data.length==0&&^35 |没有可用的选项。36 |}37 |{this.state.data.length>0&
@SamuelM。现在请检查我是否已更新了代码。只需将返回值包装为tagThis.state.data.length>0&@SamuelM。它会为缺少的值抛出一个错误ReferenceError:未定义url