javascript - 如何连接从api接收到的字符串

标签 javascript reactjs fetch-api

我想突出显示“text”元素句子中“highlight”元素中的单词。我可以成功突出显示一个句子,但无法将两个或多个句子连接在一起。我只能显示一个句子,并且用代码突出显示了该单词:

this.setState({
  text: result[0].text,
  highlight: result[0].highlight,
});

但一次不能超过多个句子。我想将 api 中尽可能多的句子与突出显示的单词动态连接起来。我尝试将状态设置为 text: result[].texthighlight: result[].highlight 但它给了我错误。正如您在 this sandbox 中看到的那样,只有当您执行 result[0].textresult[1].text 时,您会得到不同的结果,但我想连接中的所有句子动态api假设我将来会有更多句子。

react 代码如下所示:

import React, { Component } from "react";
import { render } from "react-dom";

import "./App.css";

const stripChars = word => word.replace(/[\W_]+/g, "");

class App extends Component {
  state = {
    text: "The gun is a dangerous weapon, don't kill anyone",
    highlight: ["gun", "kill"]
    // text: "",
    // highlight: []
  };

  componentDidMount() {
    fetch("https://api.myjson.com/bins/1ep1fh")
      .then(res => res.json())
      .then(result => {
        console.log(result);
        this.setState({
          text: result[0].text,
          highlight: result[0].highlight
        });
      });
  }
  render() {
    const { text, highlight } = this.state;
    const words = text.split(" ");
    return (
      <div>
        {words.map((word, i) => (
          <span key={i}>
            <span
              className={highlight.includes(stripChars(word)) && "highlight"}
            >
              {word}
            </span>
            &nbsp;
          </span>
        ))}
      </div>
    );
  }
}

export default App;

CSS 文件:

.highlight{
  background: red;
}

最佳答案

您可以在 api 调用中使用 Array.Mapjoin() 来迭代和平展数组:

  componentDidMount() {
    fetch("https://api.myjson.com/bins/1ep1fh")
      .then(res => res.json())
      .then(result => {
        let texts = result
          .map((el, i) => {
            return el.text;
          })
          .join("");
        let highlights = result
          .map((el, i) => {
            return el.highlight;
          })
          .join("").split(",");
        console.log(highlights);
        this.setState({
          text: texts,
          highlight: highlights
        });
      });
  }

result

关于javascript - 如何连接从api接收到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57866874/

相关文章:

javascript - 如何在 React 应用程序中使用 Fetch 向 Flask API 发送 POST 请求

javascript - 使用 javascript 实时预览文本

javascript - 强制文本选择(突出显示)至少为一个完整的空格分隔的单词

javascript - a.b < 0,为什么当 a.b === undefined 时不会抛出错误?

javascript - 在函数中使用设置间隔和获取

javascript - 使用 JavaScript Fetch 和 POST 发送表单数据,然后在 PHP 中处理

c# - Javascript中获取满足特定条件的数组内的数组

reactjs - 用户授权后如何在所有子组件之间传递状态?

javascript - 在我的 Firebase 应用程序中写入和读取数据的推荐方法是什么?

reactjs - 来自 react-i18next 的 initialI18nStore 来自哪里