我在子组件中从父函数调用了“ 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);
React函数组件接收到的参数是其props,它是一个对象,每个属性都具有命名属性。因此,您AddBookForm
的参数不应为booksRefresh
,而是(按照惯例)props
,然后通过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}) => {
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句