无限循环同时传递函数作为道具反应

infinate loop while passing function as prop react

我按照一些示例将函数作为 prop 传递。

Parent:

class BookList extends React.Component{
    updateBook(chosenBook){
        this.props.editBook(chosenBook); // redux func
    }

    render() {
        return ( 
            <div>
                {this.props.books.map((item, i) => (
                    <Book key={i} list={item} submitBook={this.updateBook(item)}></Book>
                ))}
            </div>;
        )
    }
}

Child:

<Button onClick={() => {this.toggle; this.props.submitBook(this.props.list);}}>Save</Button>

我得到的是一个无限循环,我知道问题出在 parent 组件上,有什么想法/其他方法吗?

因为您没有正确传递函数,所以您传递的是一个值。删除函数名称为 ()

这样写:

submitBook = {this.updateBook}

在此代码段中查看差异:

function abc(){
   return 10;
}

console.log('without ()', abc);

console.log('with ()', abc());

注意:不要忘记在构造函数中绑定updateBook方法或者使用箭头函数