使用来自中继的数据填充自动完成功能失败

时间:2016-09-02 12:25:28

标签: reactjs relayjs

我正在尝试使用来自中继的数据填充自动完成组件。看起来很简单,你可以在下面的代码中看到。请求获取时,我使用搜索词调用setVariables。现在,当我在输入中键入f时,我观察到的行为会产生网络请求并返回正确的数据。但是,(受控)输入会清除其值(自动填充组件的this.state.value''),并且自动填充不会填充建议。记录readyState会显示以下输出

logging the ready state object

events: [
  { type: "NETWORK_QUERY_START" },
  { type: "CACHE_RESTORE_START" },
  { type: "CACHE_RESTORE_FAILED" },
  { type: "ABORT" }
]

现在在输入中再次输入f,它从中继缓存中获取数据并正确填充自动完成。输入第二个字母虽然再次清除输入,但只有输入两个相同的字母才会获得数据并填充列表。

import React, { Component } from 'react'
import Relay from 'react-relay'
import Autosuggest from 'react-autosuggest'

const renderSuggestion = (suggestion) => <span>{suggestion.node.fullName}</span>
const getSuggestionValue = (suggestion) => suggestion.node.rowId

class AutoComplete extends Component {
  state = {
    value: '',
  }

  onChange = (event, { newValue }) => {
    this.setState({ value: newValue })
  }

  onSuggestionSelected = (event, selection) => {
    console.log(selection)
    this.props.onChange(selection.suggestion)
  }

  onSuggestionsFetchRequested = ({ value }) => {
    console.log('fetch requested')
    this.props.relay.setVariables({
      query: value,
      hasQuery: true,
    }, (state) => {
      console.log(state)
    })
  }

  onSuggestionsClearRequested = () => {
    this.props.relay.setVariables({
      query: null,
      hasQuery: false,
    })
  }

  render() {
    const { artists } = this.props.viewer

    const inputProps = {
      onChange: this.onChange,
      placeholder: '...',
      value: this.state.value,
    }

    return (
      <Autosuggest
        suggestions={artists ? artists.edges : []}
        onSuggestionsFetchRequested={::this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={::this.onSuggestionsClearRequested}
        onSuggestionSelected={::this.onSuggestionSelected}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        inputProps={inputProps}
      />
    )
  }
}

export default Relay.createContainer(AutoComplete, {
  initialVariables: {
    query: null,
    hasQuery: false,
  },

  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        artists: searchArtists(
          first: 10,
          search: $query
        ) @include(if: $hasQuery) {
          edges {
            node {
              id
              rowId
              fullName
            }
          }
        }
      }
    `
  }
})

我该如何解决这个问题。这种行为是预期的,还是我这方面的错误或继电器的错误?

编辑:看来 - 虽然我不确定 - 我得到的行为是由于嵌套中继容器。像Relay(Profile) -> Form -> Relay(AutoComplete)一样。

编辑2:由于Relay(Profile)重新渲染,输入会丢失其值。让shouldComponentUpdate false返回Relay(Profile)会导致预期的行为。但是我猜这不是实现它的正确方法。

0 个答案:

没有答案