[英]React component of grandparent callback doesnt re-render page after being call in grandchild
我在<grandchild>
组件中调用handle方法(更改状态),但在<grandparent>
组件中进行几次回调后停止渲染。
我试过:
使用this中的this.bind和箭头方法正确设置绑定。
每次调用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.