reactjs - 我的代码无法更新嵌套组件

标签 reactjs typescript

我尝试了 React 和 React-typist。

我有一些问题。 然后我传递一个将状态更改为“onTypingDone”的闭包并调用它,但无法正常工作。 我认为这是因为打字员可能不会重新渲染内部组件。 例如下面的代码。下面的代码不能很好地工作。

如何才能正确工作?

import * as React from 'react';
import Typist from 'react-typist';

export interface Props {}
export interface State {
    className: string
}

export MyComponents extends React.Component<Props, State> {
    constructor(props: Props)
    {
        super(props);
        this.state = { className: "before" };
    }

    switch() {
        this.setState({ className: "after" });
    }

    render()
    {
        <Typist onTypingDone={this.switch.bind(this)}>
            <div className={this.state.className}>
                <p>Hello.</p>
            </div>
        </Typist>
    }
}

最佳答案

当我深入研究代码时发现了真正的问题, 打字员正在停止重新渲染,

this.state.className 指向 MyComponents, 但 Typist 中的内容不会重新渲染, 原因是 Typist 组件内的 shouldComponentUpdate 函数

shouldComponentUpdate(nextProps, nextState) {
    if (nextState.textLines.length !== this.state.textLines.length) {
        return true;
    }
    for (let idx = 0; idx < nextState.textLines.length; idx++) {
        const line = this.state.textLines[idx];
        const nextLine = nextState.textLines[idx];
            if (line !== nextLine) {
                return true;
            }
    }
    return this.state.isDone !== nextState.isDone;
}

shouldComponentUpdate :

render() will not be invoked if shouldComponentUpdate() returns false.

您可以通过以下方式实现解决方案:

<div className={this.state.className}>
    <Typist onTypingDone={this.switch.bind(this)}>
            <p>Hello.</p>
    </Typist>
</div>

关于reactjs - 我的代码无法更新嵌套组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47020781/

相关文章:

javascript - 将 nextjs 站点部署到 netlify 时不断崩溃

node.js - 将服务器端 axios 请求的响应发送到 React/Redux 应用程序

javascript - 如何将 React 组件连接到 Quickbooks 按钮

使用 Angular 4 进行 HTML 5 拖放

javascript - Angular 2 : Unhandled Promise rejection: No provider for AuthService! ;区域: Angular

javascript - 使用 React Hooks 引用 DOM 元素

reactjs - 如何防止 React Router 中出现连续的 URL?

angular - 在 Angular 2 typescript 中将函数作为 JSON 数据传递

javascript - 如何在 typescript 中将可选参数传递给回调函数

typescript - 使用 Typescript 的 Shopify CLI