【问题标题】:React component of grandparent callback doesnt re-render page after being call in grandchild祖父回调的 React 组件在孙子调用后不会重新渲染页面
【发布时间】:2019-04-09 03:15:59
【问题描述】:

我在 <grandchild> 组件中调用句柄方法(更改状态),但在 <grandparent> 组件中的几次回调后它停止渲染。

我已经尝试过:

  1. 在构造和箭头方法中使用 this.bind 正确设置绑定。

  2. 确保每次调用 prop.callback 时都会调用回调。

这是我尝试用 graphql 服务器做的一个例子:

祖父组件


//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 次渲染一切正常,然后即使回调正在进行,也不再重新渲染。我检查&lt;grandparent&gt; 中的方法是否正在被调用,它确实被调用了,但是状态停止了变化。即使在转到新路由(反应路由器)然后回来之后,我仍然无法使用该回调更改状态。

【问题讨论】:

    标签: javascript reactjs graphql


    【解决方案1】:
    <Button onclick={(this.props.handleParentData(vars))} >Btn</Button>
    

    我认为问题在于在 onclick 属性中被调用的函数,您可能应该将它包装在另一个函数中,以便仅在您实际触发 onclick 侦听器时调用它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 2020-02-13
      • 1970-01-01
      • 2020-06-15
      • 2017-10-05
      • 1970-01-01
      相关资源
      最近更新 更多