【发布时间】:2020-06-19 16:58:57
【问题描述】:
我有一个结果列表,每次单击结果时,它都会调用我的addFunc 函数将该特定结果的详细信息作为对象添加到selectedData 列表中。目前,这在我 console.log 我的 selectedData 列表时有效。
我想要做的是显示我的selectedData 列表,每次单击结果时,该对象都会添加到列表中,我希望它反映在我的屏幕上。
我相信我必须使用状态来执行此操作,但我不太确定如何操作。感谢您的帮助。
我的代码摘要如下:
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
编辑:
我已经设法通过编辑我的代码将我的函数更改为一个状态:
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 数组中的结果。我该怎么做?
【问题讨论】:
-
selectedData需要是状态。不能像那样在外面声明(除非您希望出现无法调试的情况)。 -
提示:
constructor() { this.state = { selectedData:[] } } -
这就像一个魅力,感谢亚当!您能否告诉我如何让
joined数组显示在屏幕上,并在我向其中添加对象时更新? -
另外,如果您发表评论作为答案,我可以接受它作为解决方案
标签: javascript arrays reactjs state react-state