鍍金池/ 問答/Linux  HTML/ react,在componentDidMount里面獲取數(shù)據(jù)調(diào)用setState

react,在componentDidMount里面獲取數(shù)據(jù)調(diào)用setState為何沒有觸發(fā)重渲染?

想用react做一個搜索框,組建件傳值已經(jīng)能從input傳到list組件修改state.keyword值,但getData()函數(shù)中使用fetchJsonp獲取json數(shù)據(jù)只是初始的state.keyword的值,所以獲取數(shù)據(jù)不會改變,請問有什么方法可以解決呢?

state.keyword初始值為 jianai 通過getData方法獲取json

    componentDidMount(){
        var that = this;
        const keyword = this.props.keyword;
        var url = "https://api.douban.com/v2/book/search?q="+keyword;
        var getData = function(){
            return fetchJsonp(url)
            .then(function(response) {
                return response.json()
            }).then(function(json) {
                console.log('parsed json', json.books[0]);
            
                return json;
            }).catch(function(ex) {
                console.log('parsing failed', ex)
            })
        }

        getData().then(function(data){
            that.setState({
                author:data.books[0].author,
                imgsrc:data.books[0].image
            });             
        })
     
    }
<div className="list-book">
                    <div className="list-box">
                        <li>{this.state.author}</li>
                    </div>
                    <div className="list-box">
                        <img src={this.state.imgsrc} />
                    </div>
                    <div className="list-box">
                        <li>{keyword}</li>
                    </div>
                </div>

運(yùn)行結(jié)果如圖
圖片描述

通過搜索框修改后,keyword值變了,但getData函數(shù)沒有再次調(diào)用

圖片描述

回答
編輯回答
舊時光

componentsDidMount只會在組件加載完后執(zhí)行一次,之后更新state、props都不會執(zhí)行,除非重新加載組件。
componentWillReceiveProps在組件傳進(jìn)來的props被更改時,將被調(diào)用。
所以可以在componentWillReceiveProps函數(shù)里改變state來重新獲取數(shù)據(jù)。

2017年1月21日 07:40
編輯回答
傲寒

生命周期:
除非 你重新創(chuàng)建組件, 才會調(diào)用 componentsDidMount,
如果 你通過改變 props.
你需要 在 componentWillReceiveProps 里加入響應(yīng)的函數(shù)。

2018年7月20日 22:07