Java 腳本反應原生,將 API 查詢回應存盤為字串
你好,
請在下面找到我的本機 javascript 代碼,
它目前查詢 1 個隨機單詞并將其呈現到螢屏上,但是,我現在需要將其保存為字串
我需要將回應詞存盤為字串,然后可以進一步操作,但不記得如何將單個 JSON 回應詞存盤為字串。
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
console.log("in constructor");
// create three state variables.
// apiData is an array to hold our JSON data
// isFetched indicates if the API call has finished
// errorMsg is either null (none) or there is some error
this.state = {
apiData: [],
isFetched: false,
errorMsg: null
};
}
// componentDidMount() is invoked immediately after a
// component is mounted (inserted into the tree)
async componentDidMount() {
try {
const API_URL = "https://random-word-api.herokuapp.com/word?number=1";
// Fetch or access the service at the API_URL address
const response = await fetch(API_URL);
// wait for the response. When it arrives, store the JSON version
// of the response in this variable.
const jsonResult = await response.json();
// update the state variables correctly.
this.setState({ apiData: jsonResult });
this.setState({ isFetched: true });
} catch (error) {
// In the case of an error ...
this.setState({ isFetched: false });
// This will be used to display error message.
this.setState({ errorMsg: error });
} // end of try catch
} // end of componentDidMount()
// Remember our three state variables.
// PAY ATTENTION to the JSON returned. We need to be able to
// access specific properties from the JSON returned.
// Notice that this time we have three possible returns for our
// render. This is conditional rendering based on some conditions
render()
{
if (this.state.errorMsg) {
return (
<div className="error">
<h1>An error has occured in the API call</h1>
</div>
); // end of return.
} else if (this.state.isFetched === false) {
return (
<div className="fetching">
<h1>We are loading your API request</h1>
</div>
); // end of return
} else {
// we have no errors and we have data
return (
<div className="App">
<div className="WordTable">
<h1>Hangman - API Fetch Call</h1>
{this.state.apiData.map((word) => (
<tr>{word}</tr>
))}
</div>
</div>
); // end of return
} // end of the else statement.
} // end of render()
} // end of App class
export default App;
uj5u.com熱心網友回復:
用于JSON.stringify()將 json 陣列轉換為 String
uj5u.com熱心網友回復:
解決方法就像
this.state = {
apiDataString: "", // new added
....
};
// when response received
const jsonResult = await response.json();
// convert result in string and add in state
this.setState({ apiData: JSON.stringify(jsonResult) });
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/379004.html
標籤:javascript 反应 反应原生
