祖父级回调的 React 组件在被孙级调用后不会重新呈现页面



我在<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 渲染,然后即使回调正在进行,也不再重新渲染。我检查是否正在调用<grandparent>中的方法,它确实如此,但状态停止更改。即使在转到新路由(反应路由器(然后返回之后,我仍然无法使用该回调更改状态。

<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>
     );
}

最新更新