鍍金池/ 問答/HTML/ React中父組件在不render的狀態(tài)下傳一個動態(tài)的值給子組件,如何在子組件中

React中父組件在不render的狀態(tài)下傳一個動態(tài)的值給子組件,如何在子組件中更新?

現(xiàn)在我有一個父組件里面有一個this.state.title, 這個title在我onClick的操作進行refetch數(shù)據(jù)時會得到改變,然而父組件并不會render,我現(xiàn)在有一個子組件接受this.state.title,并想在輸入框中顯示這個title,我可以編輯他,最后在子組件中點擊button save這個信息。然而我發(fā)現(xiàn)每次父組件refetch,子組件的輸入框的字符串并不會更新。

子組件的相關(guān)代碼是這樣的
type Props = {|

productSortTitle: string,

|}

state = {

productSortTitle: this.props.productSortTitle,

};

<TextInput

  onChange={this._handleProductSortTitleChange}
  value={this.state.productSortTitle}

/>

_handleProductSortTitleChange = event => {

this.setState({productSortTitle: this._sanitizeProductSortTitle(event)});

};

我覺得是因為子組件并沒有re-render, 即使props改了它也接受不到。

完全的react新人。。。希望大神指教,百度了一下發(fā)現(xiàn)有這種玩法,也是我之前一直做的:
在React中,父子組件間的通信是通過props來傳遞參數(shù)的。一般情況下,父組件傳一個值給子組件,同時還要傳一個修改該值的方法函數(shù)。這樣,在子組件中調(diào)用這個方法函數(shù)才能修改該值,并再次傳給子組件,從而修改子組件狀態(tài)。

但是覺得好繞,因為我這個productSortTitle的操作和save都是在子組件里進行的,可以的話并不想傳回父組件,想請問一下有沒有其他方法可以使子組件rerender呢?
知道shouldComponentUpdate,寫了個
shouldComponentUpdate(nextProps: Props) {
return nextProps.productSortTitle !== this.props.productSortTitle;
}
加進去發(fā)現(xiàn)并無改變,T T

回答
編輯回答
笨尐豬

父組件fetch數(shù)據(jù)后 setState如果你沒給父組件覆蓋shouldComponentUpdate生命周期的話且繼承的Component組件的話 一定會重新render的 父組件不render 你現(xiàn)在的問題應(yīng)該是父組件不render導(dǎo)致的 先看父組件試試

2017年4月6日 20:20
編輯回答
小曖昧

父組件不render,子組件肯定是無法獲取到從父組件傳入的props的。
只有讓那個props與父組件無關(guān),直接通過connectreduxstate相關(guān)。

//父組件
const Parent = () => {
    return <Children parentProps={/*...*/}/>
}

//子組件
const Children = connect(state => state)(({subState, parentProps}) => {
 //subState與父組件無關(guān)
}
2018年1月20日 06:25
編輯回答
忠妾

給你一個demo

class Test extends React.Compont{
    constructor(props){
        super(props)
        this.state = {
            title: props.title
        }
    }
    componentWillReceiveProps(nextProps){
        // 如果確定title只有該組件修改,這個 componentWillReceiveProps 省掉
        if(this.props.title !== nextProps.title){
            this.setState({
                title: nextProps.title
            })
        }
    }
    getInput = input => this.input = input
    handleClick = () => {
        let title = this.input.value
        this,props.fun(title)  // 父組件該干嘛干嘛
        this.setState({
            title
        })
    }
    render(){
        return (
            <div>
                <input ref={this.getInput} type="text"/>
                <button onClick={this.handleClick}>Test</button>
            </div>
        )
    }
}
2018年7月25日 05:08