反应-更改状态后不会重新呈现组件

时间:2019-12-21 17:21:50

标签: javascript reactjs

我有以下内容

import React, { Component } from "react";
import Typing from "react-typing-animation";

export class InfoDisplayer extends Component {
  infos = ["this is a test", "this is another test"];

  updateDisplayedInfo() {
    if (this.state.currentIndex >= this.infos.length) {
      this.setState({
        currentInfo: this.infos[0],
        currentInfo: 0,
      });
    } else {
      this.setState(prevState => ({
        currentIndex: prevState.currentIndex + 1,
        currentInfo: this.infos[prevState.currentIndex + 1],
      }));
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      currentInfo: this.infos[0],
      currentIndex: 0,
    };

    this.updateDisplayedInfo = this.updateDisplayedInfo.bind(this);
  }

  render() {
    return (
      <Typing onFinishedTyping={this.updateDisplayedInfo}>
        {this.state.currentInfo}
      </Typing>
    );
  }
}

export default InfoDisplayer;

我正在使用https://github.com/notadamking/react-typing-animation,它是用于获取文本键入动画的组件。它有一个名为onFinishedTyping的处理程序,可在完成输入后用来执行某些操作。我正在使用它来更改组件状态以更新当前信息状态。

尽管调用了updateDisplayedInfo并且更新了currentInfo,但是该组件不会再次呈现。

为什么?我相信setState应该重新呈现该组件。

添加:在线代码
Edit epic-surf-b7pgy

感谢https://stackoverflow.com/users/11872246/keikai的编辑,您可以使用react dev工具来查看第一次输入动画后状态是否已更改

1 个答案:

答案 0 :(得分:2)

添加循环
添加Typing.Reset
请参阅文档here

Edit elated-einstein-ncc7q

import ReactDOM from "react-dom";

import "./styles.css";

import React, { Component } from "react";
import Typing from "react-typing-animation";

import "./styles.css";

const infos = ["this is a test", "this is another test"];

export class InfoDisplayer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentIndex: 0
    };
  }

  componentDidUpdate() {
    console.log(this.state.currentIndex);
  }

  updateDisplayedInfo = () => {
    this.setState({ currentIndex: this.state.currentIndex === 0 ? 1 : 0 });
  };

  render() {
    return (
      <Typing onFinishedTyping={this.updateDisplayedInfo} loop>
        {infos[this.state.currentIndex]}
        <Typing.Reset count={1} delay={500} />
      </Typing>
    );
  }
}

export default InfoDisplayer;

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <InfoDisplayer />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);