簡體   English   中英

祖父母回調中的反應組件在孫子調用后不會重新呈現頁面

[英]React component of grandparent callback doesnt re-render page after being call in grandchild

我在<grandchild>組件中調用handle方法(更改狀態),但在<grandparent>組件中進行幾次回調后停止渲染。

我試過:

  1. 使用this中的this.bind和箭頭方法正確設置綁定。

  2. 每次調用prop.callback時都要確保回調。

這是我想用graphql server做的一個例子:

祖父母成分


//Graphql constant for query
const ApolloConstant = gpl`
...etc

class Grandparent extends Component {
    constructor(props) {
        super(props);
        this.state = { vars: 'query_string' }
    }

    handler = (args) => {
        this.setState({vars: args})
    }

    render() { 
        return ( 
            // For requerying graphql with search
            <input onChange={() => this.setState(vars: e.target.value)} /> 

            <Query variable={this.state.vars}>
                ...code -> some_data_arr
                {<ChildComponent data={some_data_arr} handler={this.handler}/>}
            </Query>
         );
    }
}

子組件


//This component will take in an arr of obj and display a obj list
// if one of the obj is clicked then render a child component to display that single obj

class Child extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            singleData: null
         }
    }
    render() { 
        return (
            // Ternary operator here for conditional rendering
            {
                this.state.singleData
                ? <Grandchild data={this.state.singleData} handleParentData={this.props.handler} />
                : this.display_data(this.props.data)
            }
         );
    }

    //Method to call to display objects
    display_data = () => {
        this.props.map() => 
        <div onClick={this.setState({singleData: data})} > ...some code to display data <div/>
    }
}

孫子組件

class Grandchild extends Component {

    render() { 
        return ( 
            {...do some code with object props here}
            <Button onclick={(this.props.handleParentData(vars))} >Btn</Button>
         );
    }
}

當我測試這個時,一切都適用於前3-4個渲染,然后不再重新渲染,即使回調正在進行。 我檢查<grandparent>的方法是否正在調用它確實正在調用但是狀態停止變化。 即使在進入新路徑(反應路由器)然后回來之后,我仍然無法通過該回調改變狀態。

<Button onclick={(this.props.handleParentData(vars))} >Btn</Button>

我認為問題是在onclick prop中被調用的函數,你可能應該把它包裝在另一個函數中,所以它只在你實際觸發onclick監聽器時被調用:

handleClick = () => { 
  this.props.handleParentData(vars)
}

render() { 
    return ( 
        {...do some code with object props here}
        <Button onclick={(this.handleClick)} >Btn</Button>
     );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM