所以我有这个应用程序,它显示从API作为JSON数据提取的随机引号。这是我对React的首次尝试,因此做得并不好。最初,我将所有代码存储在一个组件中-但这显然不是最佳实践,因为我可以将多个内容拆分为多个组件,例如,引用,页脚,共享按钮。
我拆分时遇到的问题是,我不知道如何在组件文件之间共享状态(用于共享到Twitter或其他附加功能),因为我这样获取数据:
/* this function accesses the API and returns a json */
export default function fetchQuote() {
return fetch('https://programming-quotes-api.herokuapp.com/quotes/random') // fetch a response from the api
.then((response) => {
let json = response.json(); // then assign the JSON'd response to a var
return json; // return that bad boy
});
}
最初是在组件类中调用的,就像这样:
/* component for the quotes */
export default class Quote extends React.Component {
/* placeholder */
constructor(props) {
super(props);
this.state = {
quoteAuthor: "Rick Osborne",
quote: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
}
}
/* actually render things */
render() {
return (
<div className="quotes">
<h1>{this.state.quoteAuthor}</h1>
<p>{this.state.quote}</p>
<div className="button">
<button id="button" onClick={this.update}>New quote</button>
</div>
</div>
);
}
/* async fetch the quotes and reassign the variables to them once processed */
update = async() => {
let response = await fetchQuote();
console.log(response);
this.setState({
quoteAuthor: response.author,
quote: response.en
});
};
}
从我的理解来看,React的钩子似乎解决了我的问题,因为我可以使用useState
和useEffect
,它们尝试如下实现(原始的fetchQuote()
函数未受影响):< / p>
export default function Quote() {
const [author, setAuthor] = useState("Rick Osborne");
const [quote, setQuote] = useState(
"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
);
let json = fetchQuote();
useEffect (() => {
setAuthor(json.author);
setQuote(json.quote);
console.log(json);
});
return (
<div className="quotes">
<h1>{author}</h1>
<p>{quote}</p>
<div className="button">
<button id="button" onClick={async () => json = await fetchQuote()}>
New quote
</button>
</div>
</div>
)
}
但是,除了显示报价的区域显示为空并且在console.log(json)
中调用useEffect
只是返回
Promise { <state>: "pending" }
Promise { <state>: "pending" }
我可以正确使用挂钩吗?如何使用JSON数据正确更新状态?
答案 0 :(得分:3)
看来,获取的承诺没有解决。 试试这个:
export default Quote = () => {
const [author, setAuthor] = useState("Rick Osborne");
const [quote, setQuote] = useState('');
const fetchMyAPI = async () => {
let json = await fetchQuote();
setAuthor(json.author);
setQuote(json.quote);
}
useEffect(() => {
fetchMyAPI();
}, []);
return (
<div className="quotes">
<h1>{author}</h1>
<p>{quote}</p>
<div className="button">
<button id="button" onClick={fetchMyAPI}>
New quote
</button>
</div>
</div>
)
这称为fetchMyAPI onMount,并在您每次点击New Quote
时调用它。