javascript - Select 在初始更改时返回错误值

标签 javascript reactjs react-native html-select

我正在使用 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;

最佳答案

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

关于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竞争条件在使用该函数之前完成。

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

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

关于javascript - Select 在初始更改时返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43282147/

相关文章:

javascript - Node.js中的工作流引擎

javascript - 在 Normalizr 模式中设置深度关联

javascript - 如何在函数中访问数组?

javascript - 已有对象时如何在jsx样式属性中添加变量?

javascript - 如何设置 Atom 编辑器以仅使用react-native-community eslint-config?

android - 适用于 IO 但不适用于 Android 的自定义字体

javascript - 由单选按钮激活的 Bootstrap 数据切换下拉列表

javascript - 助焊剂及应用状态

javascript - ReactDOM.findDOMNode() 使用 React.Children child

react-native - 无法解析模块(Expo、React Native)