首页 > 解决方案 > 通过链接传递状态

问题描述

我对做出反应还很陌生,并想通过链接传递论点。我知道我可以通过使用 State 来做到这一点,所以我做到了。

<td>
   <Link to={{pathname:"user/"+id, state:{user_url:item.url} }} >{item.name}</Link>
</td>

这将重定向到我的 user_detail 组件,

export default class User_Details extends React.Component {

    constructor(props){
        super(props);
        this.state = {
            error : null,
            isloading: true,
            user_detail : null,
            user_url : null

        };
        if (this.props.location.state){
            this.state.user_url =this.props.location.state.user_url
        }
    }

用户可以通过重定向链接或仅通过 url 访问此 user_detail 组件,如果它通过重定向链接到达那里,那么我不必从中获取 user_url,因为它保存在状态中。但是,如果用户使用没有状态的链接,那么我首先必须获取该链接。

这可行,但是如果我使用重定向链接,我会不断收到警告错误:

index.js:1446 警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 componentWillUnmount 方法中的所有订阅和异步任务。在用户中(由 Context.Consumer 创建)

我将如何解决这个问题?

标签: javascriptreactjs

解决方案


你不能像这样操纵状态我建议你componentDidMount像这样使用 setState

    componentDidMount() {
      if (this.props.location.state){
               this.setState({
                 user_url: this.props.location.state.user_url
               });
      }
   }

推荐阅读