如何在ReactJS中使用状态更新数组 [英] How to update array using state in ReactJS

查看:710
本文介绍了如何在ReactJS中使用状态更新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结果列表,每当我单击一个结果时,它就会调用我的addFunc函数,以将该特定结果的详细信息添加为selectedData列表中的对象.目前,这在我console.log我的selectedData列表时有效.

I have a list of results, and each time I click on a result, it calls my addFunc function to add that particular result's details as an object in the selectedData list. Currently, this works when I console.log my selectedData list.

我想要做的是显示我的selectedData列表,每次单击结果时,该对象将被添加到列表中,并且我希望该对象能够反映在我的屏幕上.

What I want to do is display my selectedData list, and each time a result is clicked, the object will be added to the list, and I want that to be reflected on my screen.

我相信我必须使用状态来执行此操作,但是我不太确定该怎么做.谢谢您的帮助.

I believe I have to use state to do this, but I am not very sure how to. Thank you for your help.

我的代码摘要如下:

let selectedData = [];

const Wrapper = cb => {
  return (res, triggerClickAnalytics) => (
    <RenderItem
      res={res}
      triggerClickAnalytics={triggerClickAnalytics}
      addFunc={cb}
    />
  );
};

class Search extends Component {
  constructor(props) {
    super(props);
    this.addFunc = this.addFunc.bind(this);
  }
  addFunc(resultdata) {
    selectedData = [...selectedData, resultdata]
    console.log(selectedData)
  }
render() {
    return (
          <ReactiveList
            componentId="results"
            dataField="_score"
            pagination={true}
            react={{
              and: ["system", "grouping", "unit", "search"]
            }}
            size={10}
            noResults="No results were found..."
            renderItem={Wrapper(this.addFunc)}
          />
        </ReactiveBase>
    );
  }
}

const RenderItem = ({ res, triggerClickAnalytics, addFunc }) => {

  let { unit, title, system, score, proposed, id } = {
    title: "maker_tag_name",
    proposed: "proposed_standard_format",
    unit: "units",
    system: "system",
    score: "_score",
    id: "_id"
  };
  const resultdata = { id, title, system, unit, score, proposed };

  return (
        <Button
          shape="circle"
          icon={<CheckOutlined />}
          style={{ marginRight: "5px" }}
          onClick={() => addFunc(resultdata)}
        />
  );
};

整个代码位于此代码沙箱中: https://codesandbox.io/s/little-framework-spg1w

The whole code is in this code sandbox: https://codesandbox.io/s/little-framework-spg1w

我已经设法通过编辑代码来将功能更改为一种状态:

I've managed to change my function to a state by editing my code as such:

  constructor(props) {
    super(props);
    this.addFunc = this.addFunc.bind(this);
    this.state = { selectedData:[] }
  }
  addFunc(resultdata) {
    var joined = this.state.selectedData.concat(resultdata);
    this.setState({ selectedData: joined })
    console.log(joined)
  }

我现在需要在屏幕上的joined数组中显示结果.我该怎么办?

I now need to display the results in my joined array on the screen. How do I do this?

推荐答案

将Search.js替换为

Replace Search.js with

import React, { useState, Component } from "react";
import {
  ReactiveBase,
  DataSearch,
  MultiList,
  SelectedFilters,
  ReactiveList
} from "@appbaseio/reactivesearch";
import { Row, Button, Col } from "antd";
import { CheckOutlined } from "@ant-design/icons";

const Wrapper = cb => {
  return (res, triggerClickAnalytics) => (
    <RenderItem
      res={res}
      triggerClickAnalytics={triggerClickAnalytics}
      addFunc={cb}
    />
  );
};

class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedData : []
    }
    this.addFunc = this.addFunc.bind(this);
  }
  addFunc(resultdata) {
    this.setState(prevState => ({selectedData: [...prevState.selectedData, resultdata]}))

  }
  render() {
    return (
      <div>
        <ReactiveBase
          app="datataglist"
          credentials="mRgWyoKGQ:f47be2a6-65d0-43b6-8aba-95dbd49eb882"
          url="https://scalr.api.appbase.io"
        >
          <DataSearch
            componentId="search"
            dataField={[
              "maker_tag_name",
              "maker_tag_name.autosuggest",
              "maker_tag_name.keyword"
            ]}
            fieldWeights={[6, 2, 6]}
            fuzziness={1}
            highlightField={["maker_tag_name"]}
            placeholder="Search Tag Name"
            style={{
              marginBottom: 20
            }}
            title="Maker Tag Name"
          />
          <Row gutter={16}>
            <Col span={8}>
              <MultiList
                componentId="system"
                dataField="system.keyword"
                queryFormat="or"
                size={100}
                sortBy="asc"
                style={{
                  marginBottom: 20
                }}
                title="System"
              />
            </Col>
            <Col span={8}>
              <MultiList
                componentId="grouping"
                dataField="grouping.keyword"
                size={100}
                style={{
                  marginBottom: 20
                }}
                title="Grouping"
              />
            </Col>
            <Col span={8}>
              <MultiList
                componentId="unit"
                dataField="units.keyword"
                size={100}
                style={{
                  marginBottom: 20
                }}
                title="Unit"
              />
            </Col>
          </Row>
          <SelectedFilters />
          <ReactiveList
            componentId="results"
            dataField="_score"
            pagination={true}
            react={{
              and: ["system", "grouping", "unit", "search"]
            }}
            size={10}
            noResults="No results were found..."
            renderItem={Wrapper(this.addFunc)}
          />
        </ReactiveBase>
        <div />
      </div>
    );
  }
}

function getNestedValue(obj, path) {
  const keys = path.split(".");
  const currentObject = obj;
  const nestedValue = keys.reduce((value, key) => {
    if (value) {
      return value[key];
    }
    return "";
  }, currentObject);
  if (typeof nestedValue === "object") {
    return JSON.stringify(nestedValue);
  }
  return nestedValue;
}

const RenderItem = ({ res, triggerClickAnalytics, addFunc }) => {
  // console.log(name);

  let { unit, title, system, score, proposed, id } = {
    title: "maker_tag_name",
    proposed: "proposed_standard_format",
    unit: "units",
    system: "system",
    score: "_score",
    id: "_id"
  };
  title = getNestedValue(res, title);
  system = getNestedValue(res, system);
  unit = getNestedValue(res, unit);
  score = getNestedValue(res, score);
  proposed = getNestedValue(res, proposed);
  id = getNestedValue(res, id);

  const resultdata = { id, title, system, unit, score, proposed };

  return (
    <Row
      onClick={triggerClickAnalytics}
      type="flex"
      gutter={16}
      key={res._id}
      style={{ margin: "20px auto", borderBottom: "1px solid #ededed" }}
    >
      <Col style={{ width: "360px" }}>
        <h3
          style={{ fontWeight: "600" }}
          dangerouslySetInnerHTML={{
            __html: title || "Choose a valid Title Field"
          }}
        />
      </Col>
      <div style={{ padding: "20px" }} />
      <Col>
        <p
          style={{ fontSize: "1em", width: "300px" }}
          dangerouslySetInnerHTML={{
            __html: system || "Choose a valid Description Field"
          }}
        />
      </Col>
      <div style={{ padding: "10px" }} />
      <Col>
        <p
          style={{ fontSize: "1em" }}
          dangerouslySetInnerHTML={{
            __html: unit || "-"
          }}
        />
      </Col>
      <div style={{ padding: "10px" }} />
      <Col style={{ minWidth: "120px" }}>
        <p
          style={{ fontSize: "1em", width: "300px" }}
          dangerouslySetInnerHTML={{
            __html: proposed || "Choose a valid Description Field"
          }}
        />
      </Col>
      <div style={{ padding: "10px" }} />
      <Col>
        <p
          style={{ fontSize: "1em" }}
          dangerouslySetInnerHTML={{
            __html: Math.round(score) || "Choose a valid Description Field"
          }}
        />
      </Col>
      <Col>
        <Button
          shape="circle"
          icon={<CheckOutlined />}
          style={{ marginRight: "5px" }}
          onClick={() => addFunc(resultdata)}
        />
      </Col>
    </Row>
  );
};

export default Search;

这篇关于如何在ReactJS中使用状态更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆