onclick后,ComponentWillMount再次渲染

时间:2017-11-07 11:47:23

标签: javascript reactjs

加载页面ComponentWillMount触发getLocalStorage功能时。这有几个检查并触发search功能。当您加载页面时,它正在尝试从localStorage检索查询。当您更改输入(更改查询)并提交时,search函数应该触发但不提取..而是刷新页面并再次加载componentDidMount?然后在刷新后它完美地工作。为什么它只刷新一次?

componentWillMount(){
    this.getLocalStorage();
};

getLocalStorage = () => {
    //Check if localstorage is supported by browser
    if (typeof(Storage) !== "undefined") {

        //Check if localstorage item query is defined
        if (localStorage.getItem("query") !== null) {

            //Set query to localstorage item and go to search function
            //This works and triggers the search function
            this.setState({
                query: localStorage.getItem("query")
            },() => {
                this.search();
            });
        }

        // If localstorage item is not defined go to location
        else{
            this.getLocation();
        }
    }

    // If localstorage is not supported by the browser go to location
    else {
        this.getLocation();
    }
};

当您单击按钮时,它会触发搜索功能,但不会获取。而是再次触发componentDidMount?

<input type="text" onChange={this.handleChange} placeholder="Find your location..."/>
<button onClick={this.search}>Submit</button>

搜索功能

search = () => {

    this.setState({
        secondLoader:true
    });

    let BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?";
    let ACCES_TOKEN = "token";
    let FETCH_URL = `${BASE_URL}address=${this.state.query}&key=${ACCES_TOKEN}`;

    alert('the search function does not fetch like below instead it trigger componentDidMount again');


    fetch(FETCH_URL, {
        method: "GET"

    })
        .then(response => response.json())
        .then(json => {
            //If repsonse got zero results use amsterdam location
            if(json.status === 'ZERO_RESULTS'){
                this.setState({
                    query: 'Amsterdam'
                });
            }

            //Otherwise use query
            else {
                const geocode = json.results[0].geometry.location;

                this.setState({
                    latitude: geocode.lat,
                    longitude: geocode.lng
                });
            }

            const BASE_URL = "https://api.darksky.net/forecast/";
            const ACCES_TOKEN = "token";
            const FETCH_URL = `${BASE_URL}${ACCES_TOKEN}/${this.state.latitude},${this.state.longitude}?lang=nl&units=si`;

            fetch(FETCH_URL, {
                method: "GET",
            })
                .then(response => response.json())
                .then(json => {
                    const data = json;
                    this.setState({
                        weather: data,
                        loader: false,
                        secondLoader: false
                    });
                })
        })
};

1 个答案:

答案 0 :(得分:1)

尝试在按钮中添加type属性。我相信它令人耳目一新的原因是它的默认类型为submit。尝试使用type="button"更多信息here