作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我从子组件中的父级调用函数“booksRefresh()”,但出现错误:
TypeError: booksRefresh is not a function
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 函数组件接收的参数是它的 Prop ,它是一个具有每个属性的命名属性的对象。所以你的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();
// −−−−−^^^^^^
}
// ...
const AddBookForm = ({booksRefresh}) => {
关于javascript - react 类型错误 : x is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59663809/
我是一名优秀的程序员,十分优秀!