React-router-dom:链接到url不起作用,在url中添加7%B

问题描述 投票:0回答:1

我在网络应用程序中创建链接时遇到问题。我对 Flask 和 React 都很陌生,所以如果我没有使用正确的词汇,我很抱歉。 创建链接

<Link to='/${todo.id}'>{todo.content}</Link>
时,它会转到空的 url
http://localhost:3000/$%7Btodo.id%7D
。我知道 %7B 是括号的翻译,但我不明白为什么它不取里面的值。

我的

App.js
文件如下:

import {BrowserRouter as Router , Routes, Route} from "react-router-dom";

function App() {
  console.log('trying')
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path='/' element={<TodoPage/>}></Route>
          <Route path='/:id' element={<Show/>}></Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

我有以下功能:

import React from 'react';
import {Link} from "react-router-dom";

export const Card = ({listOfTodos}) => {
    return (
        <>
            {listOfTodos.map(todo => {
                return(
                    <ul key={todo.id}>
                        <li>
                            <Link to='/${todo.id}'>{todo.content}</Link>
                        </li>
                    </ul>
                )
            })}
        </>
    )
}
import React, {useState, useEffect} from 'react';
import {useParams} from "react-router-dom";

export const Show = () => {

    const {id} = useParams()
    const [todo, setTodo] = useState([])

    useEffect( () => {
        fetch('/api/'+id)
        .then(response => response.json())
        .then(data => setTodo(data)) 
    }, [id] ) // [id] means that if the id changes, it makes a new request

    return (
        <div>
            {todo.length >0 && todo.map(data => <div>{data.content}</div>)}  
        </div>
    )

}

最后我有了烧瓶应用程序:

from flask import Flask, jsonify, request, json
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///example.db"
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    content = db.Column(db.Text, nullable = False)

    def __str__(self):
        return f'{self.id} {self.content}'

def todo_serializer(todo):
    return {
        'id': todo.id, 
        'content': todo.content
    }

@app.route('/api', methods = ['GET'])
def index():
    # will return all the entries in the database
    todo = Todo.query.all()
    return jsonify([*map( todo_serializer, Todo.query.all()  )])

@app.route('/api/<int:id>')
def show(id):
    # to click on one to do and have the details
    return jsonify([*map(todo_serializer, Todo.query.filter_by(id=id))])


if __name__ == "__main__":
    app.run(debug=True)

提前致谢!

flask url hyperlink react-router-dom
1个回答
0
投票

问题

您已使用

"$"
和方括号字符文字对文字字符串值进行编码。

<Link to='/${todo.id}'>{todo.content}</Link>

换句话说,您要导航到的链接目标是

"/${todo.id}"
,并且某些字符将被编码,例如到
"/$%7Btodo.id%7D"

解决方案

如果要将待办事项的 id 属性注入链接目标字符串,请使用字符串模板 (

Template Literals
)。

<Link to={`/${todo.id}`}>{todo.content}</Link>

或使用

generatePath
实用函数将待办事项的
id
注入目标路径字符串。

import { generatePath } from 'react-router-dom';

...

<Link to={generatePath("/:id", todo)}> // *
  {todo.content}
</Link>

*

generatePath("/:id", todo)
之所以有效,是因为
todo
具有
id
属性。相当于
generatePath("/:id", { id: todo.id })

© www.soinside.com 2019 - 2024. All rights reserved.