reactjs - 你将如何在 Reactjs 中实现以下内容
问题描述
我是 React 的新手。
我想制作一个结果页面,其中包含用户在表单中输入搜索条件并单击该表单上的提交后将出现的产品列表。理想情况下,在用户单击表单上的提交后,我希望表单消失并显示结果页面,列出所有搜索到的产品。
我已经创建了表单,带有一个 fetch 函数将表单数据发送到 api。Api 会将结果发回,但由于我希望结果显示在我创建的结果页面中并使表单消失,我应该在这里做什么?
解决方案
我已经为您实现了类似类型的示例。请检查一下。您需要输入一个数字(例如 10)并单击按钮以获取问题。
问题搜索组件
import React, {Component} from "react";
import QuestionList from "./QuestionList";
export default class QuestionSearch extends React.Component {
state = {
amount: 0,
isLoading: false,
questions: [],
error: null
};
textHandler = (e) =>{
this.setState({amount: e.target.value})
};
fetchQuestions = () => {
console.log(this.state);
fetch(`https://opentdb.com/api.php?amount=${this.state.amount}&difficulty=hard&type=boolean`,)
.then(response => {
if (response.status !== 200) {
console.log('There was a problem. Status Code: ' + response.status);
return;
}
response.json().then(data => {
console.log(data);
this.setState({
questions: data.results,
isLoading: false
})
});
}
)
.catch(function (error) {
console.log('Error: ', error);
this.setState({error, isLoading: false})
});
};
render() {
return (
<div>
amount (type 10 in textbox): <input id="amount" onChange={this.textHandler}/>
<button onClick={this.fetchQuestions}>Click for calling API using fetch</button>
{this.state.questions.length > 0 ?
<QuestionList data={this.state}/> : null
}
</div>
);
}
}
问题列表组件
import React, {Component} from "react";
export default class QuestionList extends React.Component {
render() {
const {isLoading, questions, error} = this.props.data;
console.log(this.props, 'props');
return (
<React.Fragment>
<h1>Random Question</h1>
{error ? <p>{error.message}</p> : null}
{!isLoading && questions ? (
questions.map((questionList, index) => {
const {question, category, type, difficulty} = questionList;
return (
<div key={index}>
<p>Question: {question}</p>
<p>Question Type: {type}</p>
<p>Difficulty: {difficulty}</p>
<hr/>
</div>
);
})
) : isLoading ? (
<h3>Loading...</h3>
) : null}
</React.Fragment>
);
}
}
推荐阅读
- typo3 - TYPO3 后端在访问互联网受限的服务器上渲染时间很长
- excel - TextBox 对象自定义 - 编译错误:无效或不合格的引用
- websocket - GKE 入口超时值
- c# - 终结器如何增加 C# 中对象的寿命?
- amp-html - 如何从 amp gmail 游乐场发送带有后备纯文本电子邮件的 amp-HTML 电子邮件?
- reactjs - Button not redirecting to new page in ReactJS
- swift - SwiftUI:为什么我在 Xcode 11.3 中得到“'nil' requires a contextual type”,但它在 Xcode 11.2 中有效?
- azure-pipelines - 从 ACR 存储库获取最新的图像标签
- php - Php - 验证和错误 - 唯一名称
- android - 为什么在Android中点击推送通知后会显示白屏?