我真的需要将 forceUpdate 与 fetch API 和 ReactJS 一起使用吗

Do i really need to use forceUpdate with fetch API and ReactJS

我正在使用 React 和 fetch() 开发一个 UI,最后我这样做了:

getOperatorsList: function ( obj ) {
    fetch( 'http://x.x.x.x/operators.list',
        {
            method: 'GET',
            credentials: 'include'
        }
    ).then( function ( response ) {
            return response.json()
        } ).then( function ( json ) {
        if ( json.statusCode === 3 ) {
            cookieService.unsetCookie( 'sessId' );
        }
        obj.setState( { data: json }, () => obj.forceUpdate() );
    } ).catch( function ( ex ) {
        console.log( 'parsing failed', ex );
    } )

}

这在我的组件 Operators 中调用,看起来像这样

var Operators = React.createClass( {

    getInitialState: function () {
        return {
            data: [{ "data": "Loading" }]
        }
    },

    componentDidMount: function () {
        operatorsService.getOperatorsList( this );
    },

    render: function () {
        return (
            <div>
                <Row >
                    <Col>
                        <DataTablesCustom data={this.state.data} />
                    </Col>
                </Row>
            </div>
         );
     }
});

我已经看过 ,代码对我不起作用。

这很好用,但我真的需要使用 forceUpdate() 还是我有办法制作代码 "cleaner"?

编辑:子组件中有一个 setState 看起来像这样的 this.setState({stuff: stuff}, this.function()});。将 setState 更改为 this.setState({stuff: stuff}, () => this.function()}); 后,我能够删除 forceUpdate()

要让您的代码正常工作,您可以尝试在服务中执行此操作:

obj.setState.bind(obj)( { data: json });

但是,不需要将组件对象传递给您的服务。可以说,这不是一个好主意,因为你只是在不需要的时候耦合它们。让组件调用您的服务,然后决定如何处理数据:

 getOperatorsList: function () {
    return fetch( 'http://x.x.x.x/operators.list', {
        method: 'GET',
        credentials: 'include'
    }).then( function ( response ) {
        return response.json()
    }).then( function ( json ) {
        if (json.statusCode === 3 ) {
            cookieService.unsetCookie( 'sessId' );
        }
        return json;
    }).catch( function ( ex ) {
      console.log( 'parsing failed', ex );
    })

}

然后在你的组件中:

componentDidMount: function () {
    operatorsService.getOperatorsList()
    .then(function (json) {
       this.setState({ data: json });
    }.bind(this))
}