React-映射数组对象并传递给react-select中的options prop

时间:2019-01-24 05:21:02

标签: javascript reactjs react-select

我正在尝试映射对象数组,并使用名称键将其传递给react-select中的options属性。我可以使用常规JS做到这一点吗?我正在尝试合并this example

我的模拟数据

    mock.onGet("/dataschemas").reply(200, {
  data: [
    {
      id: "2147483599",
      selfUri: "/dataschemas/2147483599",
      name: "Book Catalog"
    },
    {
      id: "2147483600",
      selfUri: "/dataschemas/2147483600",
      name: "Business Articles"
    },
    {
      id: "2147483602",
      selfUri: "/dataschemas/2147483602",
      name: "Phone Data"
    }
  ]
});

cDM中,我用响应更新状态并将其存储在schemas

  componentDidMount() {
    axios.get("/dataschemas").then(function(response) {
      console.log(response.data.data);
      this.setState({
        schemas: response.data.data
      });
      console.log(this.state.schemas);
    });
  }

然后在我的选择组件中,将模式设置为options道具,并映射到values道具中的

<Select
  id="color"
  options={this.state.schemas}
  isMulti={false}
  value={this.state.schemas.filter(
    ({ name }) => name === this.state.name
  )}
  getOptionLabel={({ name }) => name}
  getOptionValue={({ id }) => id}
  onChange={({ value }) => this.setState({ name: value })}
  onBlur={this.handleBlur}
/>

我似乎无法在道具中获得正确的值,无法在codesandbox example的下拉选择中显示数据模式名称

关于react-select docs的与此问题有关的更多信息

3 个答案:

答案 0 :(得分:1)

<Select>组件的value属性期望单个对象/值。但是在以下代码中:

this.state.schemas.filter(
  ({ name }) => name === this.state.name
)

在数组上调用.filter将返回另一个数组。因此,您要将数组传递给value,而不是单个对象。您只需要添加一个[0]即可解开数组:

this.state.schemas.filter(
  ({ name }) => name === this.state.name
)[0]

或改用.find

this.state.schemas.find(
  ({ name }) => name === this.state.name
)

答案 1 :(得分:1)

这是一个working codesandbox

问题似乎在于您使用的是函数语法而不是粗箭头语法,结果绑定不正确,因此this.setState未定义

enter image description here

有关函数和粗箭头语法here

之间的区别的更多信息
  

这是如何工作的?我喜欢认为它是粗箭头功能   拥有或不更改“ this”的上下文。他们离开它   使其保持与函数所在的上下文相同   已创建。

对于调试此类将来的问题,我建议从查看javascript控制台错误开始-最初的提示是错误this.setState尚未定义

答案 2 :(得分:-2)

您正在尝试从响应函数范围内访问状态。 将您的componentDidMount更改为此:

fun someFunction() {
  GlobalScope.launch(Dispatchers.Main) {
    result = GlobalScope.async { callGetSomething() }.await()
    ...
  }
}

suspend fun callGetSomething(): JSONObject? = suspendCoroutine {
  Something().getSomethingFromBackend {something
    ...
    it.resume(something)
  }
}
相关问题