javascript - ReactJs 搜索按钮在 fetch 之前重新加载页面可以获取图像链接并显示它们
问题描述
我的反应应用程序有一个 CompnentDidMount() 函数,它将使用 fetch 来获取图像链接。我想更新应用程序以具有搜索按钮。因此,我不想在页面加载时正确引导图像,而是希望在用户单击搜索按钮后加载图像。但是,当我单击搜索按钮时,图像开始部分显示然后消失。我相信页面正在重新加载,因此图像正在消失
完整代码
import React, { Component } from 'react';
import './App.css';
import { FormGroup, FormControl, InputGroup, Form, } from 'react-bootstrap'
class App extends Component{
constructor(props){
super(props)
this.state = {
query: '',
fimg: []
}
this.OnSearch = this.OnSearch.bind(this);
}
OnSearch(){
this.setState({
fimg: ['https://static.zerochan.net/Emilia.%28Re%3AZero%29.full.2042398.jpg',
"https://static.zerochan.net/Rem.%28Re%3AZero%29.full.2034957.jpg"]
})
}
render(){
// this.state.fimg.map( img => console.log(img))
let images = this.state.fimg.map(( img, k) => {
return <img src={img} key={k} title="images" alt="Re:Zero" width="50%"/>
})
return(
<div className="App">
<div className="App-title"> Anime Images</div>
<Form>
<FormGroup>
<Form.Label>Search Anime</Form.Label>
<InputGroup className="formSize">
<FormControl
size="lg"
type="submit"
placeholder="Search for an Artist"
value = {this.state.query}
onChange= {event => {this.setState({query: event.target.value})}}
onKeyPress={event => {
if (event.key === 'Enter'){
this.OnSearch()
}
}
}
/>
</InputGroup>
</FormGroup>
<button onClick={() => this.OnSearch()}>search</button>
</Form>
<div className="Profile">
<div>Artist Picture</div>
<div className="loopedImages">
<div>
{images}
</div>
</div>
</div>
</div>
)
}
}
export default App;
有没有办法防止页面重新加载?或者这是除了重新加载之外的另一个问题
解决方案
添加type="button"
到您的<Button />
组件中。
推荐阅读
- oauth-2.0 - 我可以为 Gmail API 生成访问令牌,但它们不起作用
- string - 给定任意数量的不同字母,我如何找到包含所有可能的两个字母序列的最短字符串?
- java - 如何解决 If 语句使用 3 次的问题?
- jira - 根据自定义搜索检索错误总数
- swiftui - SwiftUI 向视图添加 -y 偏移量,但将视图拉伸到底部
- azure - FromBase64String 返回空字符串
- angular - 在 Ionic 应用程序中使用共享组件时生产构建失败
- macos - Mac 上的泛音和声音输入
- c++ - 成员函数中的静态变量
- c++ - For 循环 else if 语句不计算