Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在上下文之外重构逻辑。使用者_Javascript_Reactjs - Fatal编程技术网

Javascript 在上下文之外重构逻辑。使用者

Javascript 在上下文之外重构逻辑。使用者,javascript,reactjs,Javascript,Reactjs,为了得到我想要的行为,我最终把ternary嵌套在我的上下文中。消费者,它看起来很难看。 我已经尝试过重构一些逻辑,但是我无法在道具/状态改变时触发Rerender,除非我使用Context.Consumer 正在为项目开发应用程序。它使用SWAPI搜索星球大战宇宙中几乎所有的东西。我有一个根据用户的输入而变化的搜索引擎,然后加载他们的搜索结果 我一开始只是尝试在获取完成后获取要渲染的结果,在处理组件的props/state更新时遇到了一些问题,没有触发重新渲染。我们最近了解了React的上下文

为了得到我想要的行为,我最终把ternary嵌套在我的上下文中。消费者,它看起来很难看。 我已经尝试过重构一些逻辑,但是我无法在道具/状态改变时触发Rerender,除非我使用Context.Consumer

正在为项目开发应用程序。它使用SWAPI搜索星球大战宇宙中几乎所有的东西。我有一个根据用户的输入而变化的搜索引擎,然后加载他们的搜索结果

我一开始只是尝试在获取完成后获取要渲染的结果,在处理组件的props/state更新时遇到了一些问题,没有触发重新渲染。我们最近了解了React的上下文api,所以我决定在这个简单的项目中尝试使用它,尽管它100%没有必要。我读了一些书,最后读到了Context.Consumer。它非常适合我想要的东西,并在需要时触发重新渲染

  render() {
    return (
      <AppContext.Consumer>
// value here is: characterData: this.state.characterData from App.js
// characterData is in App.js' state and is updated after the fetch is successful.
        {value => (
          <section className="results-container" style={this.styles}>
            {/* FIX refactor this \/ */}
{/* 
If they haven't searched for anything, characterData doesn't exist yet,
well it's an empty {object} so it renders the 'Enter a name and hit submit!'
If they search and the results are empty, it tells them to try another name.
If the search works it renders the results.
*/}
            {value.characterData.results ? (
              value.characterData.results.length > 0 ? (
                value.characterData.results.map(item => (
                  <p style={this.styles} key={item.url} className={item.index}>
                    {item.name ? item.name : item.title}
                  </p>
                ))
              ) : (
                <span>Coulnd't find anything! Try another name or topic.</span>
              )
            ) : (
              <span className="default-results-text">
                Enter a name and hit submit!
              </span>
            )}
            {/* FIX refactor this /\ */}
          </section>
        )}
      </AppContext.Consumer>
    );
  }
我没有得到任何错误,只是想找出一个方法来清理这个。 当我试图将逻辑移到上下文之外时,我不得不退回到使用状态/道具,然后它就再也不会出现了。 我尝试过使用componentWillReceiveProps和静态getDerivedStateFromProps,但再次无法触发rerenders


托管在Zeit上:

我最终将所有逻辑重构到父组件,并返回所有逻辑的值。这让我摆脱了嵌套ternary并清理了该组件的render方法

我最终将所有逻辑重构到父组件,并返回所有逻辑的值。这使我能够摆脱嵌套ternary并清理该组件的render方法。