[英]Accessing data from service in other components
我在一次采訪中得到了以下任務,這里的任務是關於在按鈕單擊時使用 ajax 調用從 API 獲取響應並將其顯示在頁面上。
我在 App.js 中有一個頂級組件,有兩個子組件 MyButton.js 和 MyPage.js 以及 MyAPI.js 中的服務代碼
以下是文件內容:
應用程序.js
import React, { Component } from 'react';
import MyAPI from './services/MyAPI';
import MyButton from './components/MyButton';
import MyPage from './components/MyPage';
class App extends Component {
constructor() {
super();
this.state= {
'apiResponse': ''
};
}
handleButtonClick = () => {
MyAPI.getAPIResponse().then((res) => {
res => this.setState({ apiResponse })
});
}
render() {
return (
<div>
<center><MyButton onClickButton={this.handleButtonClick}></MyButton></center>
<MyPage apiResponse={this.props.apiResponse}></MyPage>
</div>
);
}
}
export default App;
我的按鈕.js
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';
const MyButton = (() => (
<div className="button-container">
<MyButton variant="extendedFab" color="primary"
onClick={this.props.onClickButton}>
Call API
</MyButton>
</div>
));
MyButton.propTypes = {
onClickButton: PropTypes.func
}
export default MyButton;
我的頁面.js
import React from 'react';
import PropTypes from 'prop-types';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Paper from '@material-ui/core/Paper';
const MyPage = (() => (
<Paper className="container">
<List>
<ListItem>
<ListItemText>Name: {this.props.apiResponse.split(" ")[0]}</ListItemText>
</ListItem>
</List>
</Paper>
));
MyPage.propTypes = {
apiResponse: PropTypes.string
}
export default MyPage;
我的API.js
import axios from 'axios';
export default {
getAPIResponse() {
return axios.get("--url to get user name and age as json--").then(response => {
return response.data;
});
}
};
此處 JSON 數據包含示例用戶的名稱,僅用於演示目的,例如: John Doe
。 根據給定的任務,我只需要在我的頁面上顯示John
。
當我運行這個應用程序時,我的MyButton.js
和MyPage.js
在日志中出現錯誤。
在MyButton.js
,錯誤位於onClick={this.props.onClickButton}
,它表示無法訪問未定義的道具。 如果我將其更改為onClick={this.onClickButton}
,則會出現錯誤,無法訪問 onClickButton on undefined。 在這里執行此操作的正確方法是什么,請幫助。
同樣適用於MyPage.js
{this.props.apiResponse.split(" ")[0]
,也是在這里使用 split 方法從John Doe
獲取名字的正確方法嗎?
您的MyButtn和MyPage都是功能組件。 要訪問props
您不需要使用this
。 在功能組件的情況下,道具被視為參數。
我的按鈕
const MyButton = ((props) => (
<div className="button-container">
<MyButton variant="extendedFab" color="primary"
onClick={props.onClickButton}>
Call API
</MyButton>
</div>
));
我的頁面
const MyPage = ((props) => (
<Paper className="container">
<List>
<ListItem>
<ListItemText>Name: {props.apiResponse.split(" ")[0]}</ListItemText>
</ListItem>
</List>
</Paper>
));
一旦響應成功,您必須存儲在變量中
var a = "jhon doe";
var data = a.split(" ");
data[0];
您可以在父組件中執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.