gpt4 book ai didi

javascript - react 不识别参数?

转载 作者:行者123 更新时间:2023-11-30 09:15:45 25 4
gpt4 key购买 nike

所以在 react 中我有一个 App 组件,它正在渲染几个子组件,如下所示:

应用

render() {
return (
//JSX inside
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path="/" component={Courses} />
<Route exact path="/courses/create" component={() => <CreateCourse email={this.state.emailAddress} pass={this.state.password} />} />
<Route exact path="/courses/:id/update" component={() => <UpdateCourse email={this.state.emailAddress} pass={this.state.password} />} />
<Route exact path="/courses/:id" component={() => <CourseDetail email={this.state.emailAddress} pass={this.state.password} />} />
<Route exact path="/signin" component={ () => <UserSignIn signIn={this.signIn}/>} /> {/*pass in the signIn() in a prop called signIn to the UserSignIn component*/}
<Route exact path="/signup" component={UserSignUp} />
{/* <Route exact path="/signout" component={UserSignOut} /> */}
</Switch>
</div>
</BrowserRouter>
);
}

在这个组件中我有参数,所以我可以通过它的 id 查看类(class):

类(class)详情

componentDidMount() {
const {match: { params }} = this.props; //I used a code snippet from this video https://scotch.io/courses/using-react-router-4/route-params
//fetch data from API
axios
.get(`http://localhost:5000/api/courses/${params.id}`)
.then(results => {
//results param came back as data from api
this.setState({
//set state by setting the courses array to hold the data that came from results
course: results.data,
user: results.data.user
});
//console.log(results); //By console logging I was able to see that I am getting each individual course's info in the data object
});
}

//this method will be for deleting a course
handleDelete() {
const { match: { params }, history } = this.props;

axios.delete(`http://localhost:5000/api/courses/${params.id}`, {
auth: {
username: this.props.email,
password: this.props.pass
}
}).then(() => {
history.push("/"); //I used the history object and have it push to the homepage, that way every time I delete a course I am redirected to (/) afterwards
});
}

当我尝试导航到使用参数的 CourseDetail 组件时遇到的错误是:

CourseDetail error

有人可以帮忙吗?

最佳答案

你需要像这样传递 props read here

component={props => <CourseDetail {...props} email={this.state.emailAddress} pass={this.state.password} />} />

传递给 courseDetails 组件的 Prop 没有任何 Prop 名称 match 并且在您的 componentDidMount 中您正在这样做

const {match: { params }} = this.props;

这里的 match 将是未定义的,因此您可以访问 params

你可以通过这个例子来理解

let a = {a:{b:1}}

let {x:{b,}} = a

上面的代码和下面的一样

"use strict";

var a = {
a: {
b: 1
}
};
var b = a.x.b;

所以最终如果在解构过程中如果你没有匹配作为你试图访问的参数

(this.props.match).params
|
|__________ This is undefined you end up `undefined.params`

关于javascript - react 不识别参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55193470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com