组件不接收道具

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

在我的家庭组件中,我读取了用户的名字,然后检查它是否有效(如果名称正确,axios会返回用户)。如果它有效,我单击按钮,我想显示仪表板组件。问题是即使名称有效,仪表板也不会从Home组件接收道具。我尝试使用componentDidUpdate,但效果不佳。我不明白为什么如果我键入一个正确的用户我的仪表板被渲染但它没有得到道具?

这是我的Home组件没有构造函数:

inputChange(event) {
    this.setState({username:event.target.value});
}

login() {
    this.setState({clicked: true})
    UsersService.validUser(this.state.username).then((user) => {
        this.setState({valid: true, user: user})
    });
}

change() {
    this.setState({clicked: false})
}

render() {
    if(this.state.clicked) {
        if (this.state.valid)
            return (
                <Redirect to={{ pathname: '/dashboard', state: { user: this.state.user } }}/>
            )
        else
            this.change;
    }
    return (
        <div>
            <input onChange={this.inputChange.bind(this)}/>
            <button onClick={this.login}>LOGIN</button>
        </div>
}

仪表板组件

export interface DashboardProps {
    user: IUser
}

interface DashboardState {
}

class Dashboard extends React.Component<DashboardProps, DashboardState> {
    public static defaultProps: DashboardProps = {
        user: {
            userId: '',
            name: '',
            phone: '',
            email: '',
            age: '',
            tag: []
        }
    }
    constructor(props: DashboardProps) {
        super(props);

        this.state = {
        };
    }

    render() {
        return (
            <div>
                <Header user={this.props.user}/>
                <div>
                    <span>Hi, {this.props.user.name}</span> <br/>
                </div>
            </div>
        );
    }
}

export default withRouter(Dashboard);
reactjs
1个回答
2
投票

尝试在仪表板组件中使用withRouterreact-router HOC,将当前的路由道具注入组件。

export default withRouter(Dashboard);

编辑:

您的州信息将在this.props.location.state.user上提供。

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