[英]How do i get pass this error Invalid hook call. Hooks can only be called inside of the body of a function component. i am using React18
this is the code这是代码
import { connect } from "react-redux";
import { useParams } from "react-router-dom";
import ExpenseForm from "./ExpenseForm";
import { editExpense, removeExpense } from '../actions/expenses';
import {useNavigate} from 'react-router-dom';
//import { withRouter } from "react-router-dom";
function EditExpensePage (props){
const { id } = useParams();
const navigate = useNavigate()
return(
<div>
<ExpenseForm
expense={props.expense}
onSubmit={(expense) =>{
props.dispatch(editExpense(id,expense))
navigate('/');
}}
/>
<button onClick={()=>{
props.dispatch(removeExpense({id: props.expense.id}));
navigate('/');
}}>Remove</button>
</div>
);
};
function MapStateToProps(state){
const { id } = useParams();
return{
expense: state.expenses.find((expense)=> expense.id === id)
};
};
export default connect(MapStateToProps)(EditExpensePage);
i am trying to edit an expense with an id so that it can render a component that has the edited item.我正在尝试使用 id 编辑费用,以便它可以呈现具有已编辑项目的组件。 so far everything is working but after editing the field the component doesnt rerender, it return an error on the console.
到目前为止一切正常,但在编辑该组件不重新呈现的字段后,它会在控制台上返回一个错误。 this is the error Invalid hook call.
这是错误无效的挂钩调用。 Hooks can only be called inside of the body of a function component
钩子只能在 function 组件的主体内部调用
The reason for the error is you have used useParams
inside MapStateToProps
which you can not use inside MapStateToProps
.错误的原因是您在
MapStateToProps
中使用useParams
,而在MapStateToProps
中无法使用。 You can do something like this:你可以这样做:
function MapStateToProps(state,ownProps){
const { id } = ownProps.match.params;
return{
expense: state.expenses.find((expense)=> expense.id === id)
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.