我在componentDidMount() {
if (localStorage.getItem("JWT")) {
this.setState({logged_out_redirect: false});
}
}
组件中调用一个handle方法(以更改状态),但是在<grandchild>
组件中进行了两次回调后,它停止呈现。
我试图:
设置正确地与构造方法和箭头方法中的this.bind绑定。
确保每次调用prop.callback时都调用回呼。
这是我尝试使用graphql服务器的示例:
祖父母组件
<grandparent>
子组件
//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/>
}
}
当我对此进行测试时,所有操作都适用于前3-4个渲染,然后即使进行了回调,也不再需要重新渲染。我检查是否正在调用class Grandchild extends Component {
render() {
return (
{...do some code with object props here}
<Button onclick={(this.props.handleParentData(vars))} >Btn</Button>
);
}
}
中的方法,是否正在调用,但是状态停止更改。即使转到新路由(反应路由器)然后返回,我仍然无法通过该回调更改状态。
答案 0 :(得分:0)
<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>
);
}