首页 > 解决方案 > 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;

有没有办法防止页面重新加载?或者这是除了重新加载之外的另一个问题

标签: javascriptreactjsbutton

解决方案


添加type="button"到您的<Button />组件中。


推荐阅读