【问题标题】:Using React Palette and set state使用 React Palette 并设置状态
【发布时间】:2019-01-29 00:29:58
【问题描述】:

我正在使用react-palette 提取鲜艳的色彩。我在渲染方法中有这个:

          <Palette image={this.state.img.src}>
                {palette => {
                    this.setState({vibrantColors:palette.vibrant});
                    console.log(palette);
                    return(
                    <div>
                        Text with the vibrant color
                    </div>
                )}}
            </Palette>

我想要的是用这些颜色设置状态,但在上面的例子中,我收到了这个错误:

已超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

我知道为什么会出现此错误,并且在渲染方法中设置状态是不好的做法,但我不知道如何使用该库并使用它设置状态。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您似乎正在从渲染内部执行 setState,这将触发渲染,该渲染将再次设置状态等...

    我。因此,一种解决方法是将&lt;Palette&gt; 标签向上移动。如果您想继续使用调色板进行渲染,这通常很有用。

    <Palette image={this.state.img.src}>
      {palette => {
        // no need to seState, we can just use it here or pass it to handlers
        // you know... the react way
        return <div>Text with the vibrant color</div>;
      }}
    </Palette>
    

    二。现在,另一种方法是,如果你 真的 必须将调色板存储在 state 或某事(也许你有你的理由)是查看 react-palette 是如何编码并使用底层的给我们调色板的神奇召唤:

    1. 查看Palette.js,我们看到一个名为getImagePalette 的内部实用程序函数的用法
    2. 接下来,查看getImagePalette,我们发现它实际上只是一个npm 包node-vibrant 的包装器
    3. 从 node-vibrant 的 documentation 我们看到我们可以只使用以下内容(而不是 react-palette)
    # install the version ^3.0.0
    yarn add "node-vibrant@^3.0.0"
    # or npm install --save "node-vibrant@^3.0.0"
    
    import * as Vibrant from 'node-vibrant';
    //...
    
    doStuffWithPalette = (imgSrc) => {
      Vibrant.from(imgSrc).getPalette()
        .then(palette => {
          // do what ever you want with palette, even setState if you want to, just avoid calling it from a render/componentWillUpdate/componentDidUpdate to avoid having the same error you've got in the first place
        })
        .catch(error => {
          // handle errors
        });
    }
    

    【讨论】:

    • 感谢您的回答,我收到worker.js Uncaught TypeError: CreateListFromArrayLike called on non-object 的代码与您的(第三个解决方案)完全相同。
    • @gdfgdfg 我更改了它的导入语句也许这会解决它
    • 我正在使用和他们的文档。您之前的示例及其文档 - 结果相同。
    • 以某种方式通过 npm/yarn 安装 node-vibrant 会安装包含此问题的 alpha 版本。相反,安装版本“^3.0.0”会完美运行
    • @gdfgdfg 我更新了答案以考虑到依赖项的正确安装
    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2019-08-23
    • 2020-02-09
    • 1970-01-01
    • 2018-12-25
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多