鍍金池/ 問答/HTML/ React setState無效

React setState無效

如下代碼所示,想通過點擊事件將category數(shù)組的最后一個值在this.option中賦給categoryId,但是在onSearchClick中對option進行state的更新,發(fā)現(xiàn)并沒起作用,我打斷點了this.state.category數(shù)組是有值的但是打印出來一直是原始值,求解為什么這個optionstate沒更新,然后我該怎么做?

    state = {
        collapsed: false,
        options: [],
        option: {
            categoryId: '',
            dateRange: [],
            text: ''
        }
    };
    //...
    render() {
        return (<div><Cascader name="category" value={this.state.category} style={{width:300}} options={options} placeholder={"類目"} onChange={this.onCascaderChange}
                                          changeOnSelect/><Button type="primary" icon="search" onClick={this.onSearchClick}>過濾</Button><ArticleListManage option={this.state.option}/></div>);
    }
    onSearchClick = () => {
            if (this.state.category && this.state.category.length) {
                this.setState({option: {...this.state.option, categoryId: this.state.category[this.state.category.length - 1]}}, () => {
                    console.log(this.state.option);
                });
            }
    }
回答
編輯回答
貓小柒

if (this.state.category && this.state.category.length) 你這個判斷能走進去?

2018年6月13日 22:16
編輯回答
夢若殤

我把categoryId寫死試了一下,是可以獲取到更新后的this.state.option,那問題應(yīng)該出在this.state.category上了

2017年2月17日 07:38
編輯回答
無標(biāo)題

看看這個鏈接 問題測試地址;不知道樓主如何定位的問題,click肯定可以執(zhí)行setstate,樓主的代碼里面state里看不到category這個值,所以我也不好定位問題

2017年5月2日 22:31
編輯回答
旖襯

試試這樣寫

let _option = Object.assign({}, this.state.option)
_option['categoryId'] = this.state.category[this.state.category.length - 1]
this.setState(() => ({option: _option}))
2017年10月6日 03:45