簡體   English   中英

我如何從道具訪問我的反應組件中的歷史記錄?

[英]how can i access the history in my react components from props?

所以我試圖從我正在處理的組件中的道具中獲取歷史 object 並且它總是打印錯誤這是 class 我正在嘗試在其中使用歷史 object

import React from 'react';

const Admin = (props) => {
return (
    <React.Fragment>
        <h1>Admin</h1>  
        <button 
        onClick={()=>this.props.history.push("/edit/new")}
        type="button" className="btn btn-primary btn-lg m-1">
            Add
        </button>
        <table className="table">
                <thead>
                    <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Price</th>
                    <th></th>
                    <th></th>   
                    </tr>
                </thead>
                <tbody>
                    {props.prod.map(prod1 =>(
                        <tr key ={prod1.id}>
                            <td>{prod1.name}</td>
                            <td>{prod1.price}</td>
                            <td>                                   
                                <i 
                                onClick={()=>this.props.history.push(`/edit/${prod1.id}`)
                                }
                                className="fas fa-edit"></i>
                       
                            </td>
                            <td>
                                <span onClick={()=>props.delete(prod1)}>                        
                                    <i className ="fas fa-trash  m-2" ></i>
                                </span>
                            </td>   
                        </tr> 
                    ))}
               
                    
                </tbody>
            </table>






    </React.Fragment>
);

}

導出默認管理員;

和 app.jsx 我在這樣的路線中調用它

                            <Route path="/admin" element = {<Admin
                        prod = {this.state.Product}
                        delete={this.deleteEntery}
                        editing = {this.editElement}
                        />}/>

您尚未導入 useHistory 鈎子並使用它聲明歷史。

將此添加到導入:

import { useHistory } from 'react-router-dom'

在 function 中聲明歷史記錄:

const history = useHistory()

首先,您沒有將“歷史”作為道具傳遞給管理組件,如果您想在組件中使用歷史 object,您只需導入它並使用它(無需將其作為道具傳遞)。

// Import it at the top of your file
import { useHistory } from 'react-router-dom'

// Call this hook inside your functional component, history variable has all the required properties
const history = useHistory()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM