选择在初始更改时返回错误的值

时间:2017-04-07 15:40:59

标签: javascript reactjs select react-native option

我使用的是React,jQuery和NewsAPI。当用户更新所选选项时,请求和状态应该更改。但是,当Onchange函数执行时,它返回错误的值。函数再次执行后,该值将被一个索引关闭。有人能指出我正确的方向,而不是粗鲁:)。

import React, { Component } from 'react';
import $ from 'jquery';
import Posts from './Components/Posts';
import './style/Content.scss';


class Content extends Component {

    constructor(props){
        super(props);
        this.state = {
            posts: [],
            value: 'the-verge'
        }

        this.change = this.change.bind(this);
    }

    //Ajax Request
    getNews() {
        $.ajax({
            url: 'https://newsapi.org/v1/articles?source='+ this.state.value + '&sortBy=latest&apiKey=' + api,
            dataType: 'json',
            cache: true,
            success: function(data) {
                this.setState({ posts: [data] }, function() {
                    console.log(data);
                })
            }.bind(this),
            error: function(xhr, status, err) {
                console.log(err);
            }
        })
    }

    // Change the request depending on selected option
    change(event){
        event.preventDefault();
        this.setState({value: event.target.value});
        this.getNews();
    }

    componentWillMount(){
        this.getNews();
    }

    componentDidMount() {
        this.getNews();
    }

    componentWillReceiveProps(){
        this.change();
    }

    render() {
        return (
            <div className="Content">
                <div className="Search">
                    <h2>It's all in one place</h2>
                    <div className="Search__wrap">
                        <select value={this.state.value} onChange={this.change}>
                            <option defaultValue value="the-verge">Tech Verge</option>
                            <option value="techcrunch">Tech Crunch</option>
                            <option value="time">Time</option>
                            <option value="bbc-sport">BBC Sport</option>
                        </select>
                    </div>
                </div>
                <Posts posts={this.state.posts} />
            </div>
        );
    }
}

export default Content;

1 个答案:

答案 0 :(得分:0)

我不确定这是否正确,但是通过浏览代码,这对我来说是最明显的。

关于setState的一个重要事项是,并非本质上同步。由于在一个函数中可能有多个setState调用,因此它们被批处理并异步执行。因此,调用getNews时状态可能没有更新。

解决方案?将值显式传递给getNews函数。

change(event){
    event.preventDefault(event.target.value);
    this.setState({value: event.target.value});
    this.getNews();
}

然后:

getNews(value) {
    $.ajax({
        url: 'https://newsapi.org/v1/articles?source='+ value + '&sortBy=latest&apiKey=' + api,
        dataType: 'json',
...

这样您就可以在使用该功能之前担心setState竞争条件

您必须在this.state.valuecomponentDidMount中使用componentWillMount。小提示:您只需要在其中一个上获取API,选择您要使用的API并删除另一个,这是多余的:)

此外,在this.change中调用componentWillReceiveProps会触发错误,因为您没有传递任何事件。