如何更新反应状态

时间:2020-06-17 11:38:50

标签: javascript reactjs redux react-redux react-hooks

我有一个搜索结果列表。每个结果都有一个onclick函数。我想显示用户单击的每个结果,现在,我可以使用此功能将用户单击的每个结果添加到数组:

let selectedData = []

function addFunc(resultdata){
    console.log(resultdata)
    selectedData = [...selectedData, resultdata]
    console.log(selectedData)
  };

我是React的新手,但是我知道这不是正确的方法,我可能不得不使用状态或react挂钩。问题在于,因为我使用Elasticsearch输出结果,所以结果在函数中而不是在主类中。像这样:

class Search extends Component {
    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={RenderItem}
                     />
          </ReactiveBase>
          <div>
          </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;
  }


  function RenderItem(res, triggerClickAnalytics) {
    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>
      );
  }

基本上,我的ReactiveList组件可以显示结果。这将调用RenderItem函数,该函数将在屏幕上显示数据。在我的函数中,我有一个名为resultdata的列表,其中包含单击每个结果时需要的所有数据。这可行,但是我需要它显示在屏幕上。

我不能使用状态,因为我有一个功能。而且我不能使用钩子,因为它不是主要功能。难道我做错了什么?除此之外,还有其他选择吗?

即使您无法提供完整的答案,我也希望您能找到我应该朝哪个方向发展的任何技巧。

2 个答案:

答案 0 :(得分:1)

状态是异步的,因此不会像这样更新:

function addFunc(resultdata){
    console.log(resultdata)
    selectedData = [...selectedData, resultdata]
    console.log(selectedData)
  };

并且您正在使用一个类,因此无法useHooks,但是setState将回调作为第二个参数

function addFunc(resultdata){
    console.log(resultdata)
    this.setState({selectedData: [...selectedData, resultdata]}, () => console.log(selectedData))
  };

因此,如果您继续使用Class方法,这将允许您使用setState并利用其中的回调函数

在钩子中也有一个回调函数,但是它不能完全一样

答案 1 :(得分:0)

将addFunc放在父组件中,并通过导出将RenderItem函数设为React Functional组件。然后将addFunc作为功能组件从父组件提供到RenderItem组件。这样,您可以在onClick事件中调用该函数。可以从addFunc更新任何父状态。您也可以为函数调用提供必要的参数。