简体   繁体   English

如何将 ReactJS 上的参数传递给 setState

[英]How to pass a parameter on ReactJS to setState

I have a function that calls on my ReactJS app:我有一个 function 调用我的 ReactJS 应用程序:

Charts.createNpsGraficoRespostas(nps_respostas_vida, chart_nps_vida , self)

This is the code of the function:这是 function 的代码:

export function createNpsGraficoRespostas(array_nps_respostas, state_parameter, self){
...
self.setState({ state_parameter : chart_nps })
...
}

Did you see the parameter "state_parameter", I want to pass the value "chart_nps_vida" as a parameter to the setState function, but this it is not working.你看到参数“state_parameter”了吗,我想将值“chart_nps_vida”作为参数传递给setState function,但这不起作用。

This is what I want, but I want to use a parameter instead of use directly "chart_nps_vida".这就是我想要的,但我想使用一个参数而不是直接使用“chart_nps_vida”。

    self.setState({ chart_nps_vida: chart_nps })

How can I get to make this works?我怎样才能使它起作用?

Assuming state_parameter is a string, this should work.假设 state_parameter 是一个字符串,这应该可以工作。

  export function createNpsGraficoRespostas(array_nps_respostas, state_parameter, self){
    ...
    self.setState({ [state_parameter] : chart_nps })
    ...
    }

You're asking to use the variable parameter name as the object fieldname.您要求将变量参数名称用作 object 字段名称。 This cannot be done.这是无法做到的。 The best solution would be this:最好的解决方案是:

Charts.createNpsGraficoRespostas(nps_respostas_vida, {chart_nps_vida: chart_nps_vida} , self)

export function createNpsGraficoRespostas(array_nps_respostas, state_parameter, self){
    ...
    self.setState(state_parameter)
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM