即使 URL 包含参数,match.params 也会返回空

Posted

技术标签:

【中文标题】即使 URL 包含参数,match.params 也会返回空【英文标题】:match.params returns empty even when URL contains params 【发布时间】:2021-02-08 21:40:02 【问题描述】:

我想在单击特定 ID 进行预订时对表单进行编辑,以便将我的 ID 中的值传递到编辑表单。但是即使 URL 包含参数,match.params 也会返回空值。我该如何解决这个问题?

这是我编辑的预订文件:

export default function AdminEdit(props) 
    const [CategoryList, setCategory] = useState([]);
    const [data, setData] = useState(
        date: "",
        firstName: "",
        lastName: "",
        phone: "",
        email: "",
        noPersons: "",
        time: "",
    );

    useEffect(() => 
        const _id = props.match.params.id;
        console.log(props.match.params.id);
        console.log(_id);

        Axios.get(config.API_HOST_ORIGINAL + `/adminbookings/` + _id, 
            headers: 
                'Authorization': 'Bearer ' + config.getToken()
            
        ).then(res => 
            setData(res.data)
            console.log("Logged res data:", res.data);

        ).catch(err => console.error(err))
    , []);

    function submit(e) 
        e.preventDefault();
        Axios.post(config.API_HOST_ORIGINAL + '/bookings/', 
            headers: 
                'Authorization': 'Bearer ' + config.getToken()
            
        ).then(res => 
            console.log(res.data);
            const myData = [...CategoryList, res.data]
            setCategory(myData)
        ).catch(err => console.error(err))
    

    function handle(e) 
        const newData =  ...data 
        newData[e.target._id] = e.target.value;
        setData(newData);
    


**Another other file:
This is where I take in all the bookings**

const Bookings = (props) => 
Some hooks...

  function Update(_id) 
    console.log("Log this shiiiet to console", _id);
    props.history.push("/adminedit/" + _id);
  

return 
<>
    <td>
        <button type="button" 
        onClick=() => Update(bookings._id) 
         className="btn btn-primary btn-sm">Edit</button>
     </td>
</>


export default Bookings;

Recives this warning!

【问题讨论】:

【参考方案1】:

您应该使用来自react-router-domuseParams 钩子。

你还应该在useEffect之外定义id

import 
  useParams
 from "react-router-dom";
...
let  id  = useParams();
...
useEffect(() => 
, [])

【讨论】:

以上是关于即使 URL 包含参数,match.params 也会返回空的主要内容,如果未能解决你的问题,请参考以下文章

无法读取未定义的属性“参数” - 无法获取产品 ID

react-router 同一路由,参数不同,页面没有刷新

mapStateToProps ownProps 参数为空

[react-router] React-Router怎么获取URL的参数?

React Router 更改参数不会触发 componentWillRecieveProps

this.props.match.params 授权后传入子组件