为什么“this.props.match.params.authorName”在ReactJS中给出了未定义/空值

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (112)

我试图获取authorName发送的查询参数,因此我可以获取该值并进行搜索MongoDB

FilterBooks通过另一个名为的组件调用组件Authors

这是我的 Authors.jsx

import React, {Component} from 'react';
import axios from 'axios';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom'
import FilterBooks from './filter-books'

const SelectOption = (props) => (
        <option value={props.author.firstName}>{`${props.author.firstName} ${props.author.lastName}`}</option>
)

export default class Authors extends Component{

    constructor(props){
        super(props);
        this.state = {
            authorArray: [],
            authorName: ''
        }
        this.onChange = this.onChange.bind(this);
    }

    componentDidMount(){
        axios.get('http://localhost:4000/books/authors')
        .then(res => {
            this.setState({
                authorArray: res.data
            });
        });
    }


    getAuthors(){
        return this.state.authorArray.map((currentAuthor, id) => {
            return <SelectOption author={currentAuthor} key={id} />
        });
    }

    onChange(e){
        this.setState({
            authorName: e.target.value
        });

    }


    render(){
        return(
            <Router>
            <div className="container">
                <h3>Authors List</h3>

                <div className="row">
                    <div className="col-md-12 text-center">
                    <select
                    value={this.state.authorName}
                    onChange={this.onChange}
                    className="form-control" id="authors" name="authors">
                        <option>- Author List -</option>
                        {this.getAuthors()}
                    </select>
                    <br />
                    {/* <Link  to={`/authors/${this.state.authorName}`} className="btn btn-success" >View Books</Link> */}
                    <Link  to={`/authors/${this.state.authorName}`} className="btn btn-success" >View Books</Link>
                    </div>
                </div>

            </div>
            {/* <Route path={`/authors/${this.state.authorName}`} exact Component={FilterBooks} /> */}
            <Route path={`/authors/${this.state.authorName}`} component={FilterBooks}/>
            </Router>
        );
    }
}

这是我的 FilterBook.jsx

import React, {Component} from 'react'
import axios from 'axios';

export default class FilterBooks extends Component{

    constructor(props){
        super(props);
    }

    componentDidMount(){
        axios.get("http://localhost:4000/books/authors/" + this.props.match.params.authorName)
        .then(res => {
            console.log(res.data);
        }).catch(err => {
            console.log(err);
        });
    }

    render(){
        return(
            <div>
                <h1>Hello Books</h1>
            </div>
        );
    }
}

这是我server.js处理后端的。在这里,我删除了其他端点,因此这段代码看起来简短,清晰。

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const BookDB = require('./book-dbmodel');
const AuthorDB = require('./author-dbmodel');

const app = express();
const router = express.Router();

app.use(bodyParser.json());
app.use(cors());
app.use('/books', router);

//connect to books database
mongoose.connect('mongodb://127.0.0.1:27017/books', {useNewUrlParser: true});

const connection = mongoose.connection;
connection.once('open', () => {
    console.log("Connected to MongoDB via port 27017");
});

app.listen(4000, () => {
    console.log('Listening to port 4000');
});


//get books by author name http://localhost:4000/books/authors/authorName
router.route('/authors/:authorName').get((req, res) => {
    let authorName = req.params.authorName;
    BookDB.find({firstName: {$regex: `${authorName}`, $options: "i"}}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});

但这是我的输出,这是一个空输出:

有人可以帮帮我吗?

提问于
用户回答回答于

要将URL路径的一部分作为参数,您应该像这样定义它

<Route path='/authors/:authorName' component={FilterBooks}/>

然后,您可以在组件内访问它

this.props.match.params.authorName

扫码关注云+社区

领取腾讯云代金券