如何在新状态道具中访问其他状态/属性值

时间:2019-03-20 19:56:29

标签: javascript reactjs ecmascript-6

我想访问新状态道具中的状态/属性值。实际上,我已经有一个状态属性,用于存储Item=5的值,并创建了UrlParam,用于存储URL,但我需要在URL属性中使用Item数值。我是React的新手,请有人帮我怎么做?

我没有得到数值,我正在得到字符串。您可能会在附件中看到。

代码

    this.state={    
    Item : 5,
    Skip:0,
    urlParams:'http://localhost:3001/meetups?filter[limit]=Item&&filter[skip]=Skip'
    }

2 个答案:

答案 0 :(得分:2)

之后设置。

this.state={    
    Item : 5,
    Skip:0,
    urlParams:''
}

this.setState({ urlParams: 'http://localhost:8001/parties?filter[limit]=' + this.state.Item + '&filter[skip]=' + this.state.Skip })

OR

this.setState({ urlParams: `http://localhost:8001/parties?filter[limit]=${this.state.Item}&filter[skip]=${this.state.Skip}` })

您还可以创建函数,以在Item或Skip值更改时随时更新网址

updateItem(newValue) {
   this.setState({ 
      Item: newValue, 
      urlParams: `http://localhost:8001/parties?filter[limit]=${newValue}&filter[skip]=${this.state.Skip}`
   })
}

答案 1 :(得分:1)

如果我对您的理解正确,那么您想在Item状态下使用urlParams状态。如果不使用某种辅助函数就无法在状态声明中完成此操作,因此更好的选择是调用setState()以便在事实之后声明urlParams

在React组件中,看起来可能像这样:

state = {
  Item: 5,
  Skip: 0,
  urlParams: "",
}

componentDidMount() {

  ...

  this.setState((prevState) => { 
    urlParams: `filter[limit]=${prevState.Item}&&filter[skip]=${prevState.Stem}`
  }

  ...

}

如果您是React的新手,这可能看起来很麻烦,但这是最好的方法,因为您永远不要直接修改状态。

// good
this.setState((prevState) => ...)

// bad
this.state.urlParams = `...`

阅读this section of the docs了解更多信息。

相关问题