【问题标题】:ReactJS Router not rendering componentReactJS路由器不渲染组件
【发布时间】:2020-05-25 01:00:27
【问题描述】:

我在下面的代码中遇到了路由路径<Route path="customers/:id" render={(props) => <CusDataForm {...props}/>}/> 的问题:

import CusDataCtrl from './cusdata/CusDataCtrl'
import CusDataForm from './cusdata/CusDataForm'

class App extends Component {
  render() {
    return (      
        <BrowserRouter>
            <Switch>                            
                <Route exact path="/customers" component={CusDataCtrl} />                  
                <Route path="customers/:id" render={(props) => <CusDataForm {...props}/>}/>
            </Switch>
        </BrowserRouter>      
    );
  }
}
export default App;

如果我使用&lt;Route exact path="/customers/:id" component={CusDataForm} /&gt;,组件会正确渲染;但是,我需要将一些道具传递给这个组件。

我的调用组件是这样定义的:

class CusDataGrid extends Component {
    constructor(props) {
        super(props)
        this.state = {data: []}
    }
    componentDidMount() {
        let me = this;
        dbFetch("customers",data => me.setState({data:data}));
    }
    callEdit = e => {
        let recid = e.target.getAttribute("data")
        this.props.history.push("/customers/"+recid);
    }
    render() {
        const rows = this.state.data.map((row, ndx) => {
            return (
                <div key={ndx}><button data={row.recordid} className="waves-effect waves-light btn-small" onClick={this.callEdit}>Edit</button></div>
            );
        });
        return (
            <div id="cusdata"><div className="data-scrollable">{rows}</div></div>
        );
    }
};
export default CusDataGrid;

我的目标组件是:

class CusDataForm extends Component{    
    componentDidMount = () =>{     
        this.setState({id: this.props.id ? this.props.id : ""});
    }    
    render(){
        return(<div>HELLO</div>)
    }
}
export default CusDataForm;

请让我知道我做错了什么。谢谢!

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    你可以使用钩子 useParams

        <Switch>
          <Route path="/:id" children={<Child />} />
        </Switch>
    
        function Child() {
        // We can use the `useParams` hook here to access
        // the dynamic pieces of the URL.
        let { id } = useParams();
    
         return (
         <div>
          <h3>ID: {id}</h3>
         </div>
        );
       }
    

    official documentation

    【讨论】:

    • useParams() 不是只用在函数组件中,不用于类组件吗?
    • 我还需要给这个组件传递props。
    • 查看历史和位置对象reacttraining.com/react-router/web/api/history你在道具中有它。关于传递道具:您总是将道具传递给组件 VIA 状态管理系统,如 redux 或直接从父级传递到子级。路由器不应该乱用道具
    猜你喜欢
    • 1970-01-01
    • 2019-01-20
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多