繁体   English   中英

在 Context.Consumer 之外重构逻辑

[英]Refactoring logic outside of Context.Consumer

为了得到我想要的行为,我最终在我的 Context.Consumer 中嵌套了三元,它看起来很丑。 我已经尝试重构一些逻辑,但是除非我使用 Context.Consumer,否则我无法在道具/状态更改时触发重新渲染。

为项目开发应用程序。 它使用 SWAPI 搜索《星球大战》宇宙中的几乎所有内容。 我有一个根据用户的输入而改变的,然后加载他们的搜索结果。

我一开始只是试图在获取完成后渲染结果,并且在处理组件的道具/状态更新时遇到了一些问题,不会触发重新渲染。 我们最近了解了 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>
    );
  }

我没有收到任何错误,只是想找出一种方法来清理它。 当试图将逻辑移到 Context.Consumer 之外时,我必须回退到使用状态/道具,然后它永远不会重新渲染。 我尝试使用 componentWillReceiveProps() 和 static getDerivedStateFromProps() 但再次无法触发重新渲染。

托管在 Zeit 上: https://starwars-search-nm7mk0268.now.sh/

我最终将所有逻辑重构为父组件,并仅返回所有逻辑的值。 这让我可以摆脱嵌套的三元组并清理这个组件的渲染方法

暂无
暂无

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

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