反应类型错误:x 不是函数

新手上路,请多包涵

我在子组件中从父级调用函数“booksRefresh()”,但出现错误:

TypeError: booksRefresh 不是函数

我不知道为什么,因为“booksRefresh”是一个函数。有人可以帮我解释为什么会出现此错误吗?

这是我的代码:

 import React, {useState} from "react";
import {Redirect} from "react-router";
import {addBook} from "../api/api";
import {Button} from "react-bootstrap";

const AddBookForm = (booksRefresh) => {
    const [title, setTitle] = useState();
    const [description, setDescription] = useState();
    const [submitted, setSubmitted] = useState(false);

    const postRequestHandler = () => {
        addBook(title, description);
        booksRefresh();
    }
...
 return (
        ...
            <Button type="submit" onClick={postRequestHandler} variant="outline-success">Add</Button>
        </div>
    )

家长:

 function App({history}) {
  ...
    const [changeInBooks, setChangeInBooks] = useState(0)

    const booksRefresh = () => {
        let incrementChangeInBook = changeInBooks + 1;
        setChangeInBooks(incrementChangeInBook)
    }
return (
        <div className="App">
            <header className="App-header">
                ...
                            <Button variant="outline-success" onClick={() => history.push("/new-book")}>
                                {ADD_BOOK}</Button>
                ...
            </header>
            <Switch>
                ...
                <Route path="/new-book" exact render={() =>
                    <AddBookForm
                        booksRefresh={booksRefresh}/>
                }/>
               ...
            </Switch>
        </div>
    );
}

export default withRouter(App);

原文由 wer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 282
2 个回答

React 函数组件接收的参数是它的 props ,它是一个对象,每个属性都有命名属性。 So your AddBookForm ’s parameter shouldn’t be booksRefresh , but (by convention) props , and then you use it via props.booksRefresh() :

 const AddBookForm = (props) => {
// −−−−−−−−−−−−−−−−−−^^^^^
    const [title, setTitle] = useState();
    const [description, setDescription] = useState();
    const [submitted, setSubmitted] = useState(false);

    const postRequestHandler = () => {
        addBook(title, description);
        props.booksRefresh();
// −−−−−^^^^^^
    }

    // ...

或者,如果它是唯一的道具,您可以 像 adiga 展示的那样 使用解构:

 const AddBookForm = ({booksRefresh}) => {

原文由 T.J. Crowder 发布,翻译遵循 CC BY-SA 4.0 许可协议

const AddBookForm = ({booksRefresh}) => {
        const [title, setTitle] = useState();
        const [description, setDescription] = useState();
        const [submitted, setSubmitted] = useState(false);

        const postRequestHandler = () => {
            addBook(title, description);
            booksRefresh();
        }

试试这个我希望它有效

因为 props.booksRefresh 是一个函数

原文由 Man 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题