我有一个GetData.js组件,该组件获取API数据并将其设置为数组。我想在多个其他组件中访问该数组数据,并以多种不同方式对其进行操作。
例如,我希望能够执行以下操作:
import APIdata from './GetData';
var data = APIdata.object;
var result = [];
if (data) {
for (var i = 0; i < data.length; i++) {
if (data.form_values["6f71"] === "KeyWord") {
result.push(data)
}
}
}
答案 0 :(得分:1)
您正在寻找一种相当简单的容器组件,道具和状态用法。
这是一个人为的例子:
import React, {Component} from 'react';
import OtherComponent1 from './OtherComponent1';
import OtherComponent2 from './OtherComponent2';
class GetDataComponent extends Component {
constructor() {
super(props);
this.state = {
data: []
}
}
fetchMyData() {
const resultingArray = ...
this.setState({data: resultingArray});
}
componentDidMount() {
this.fetchMyData();
}
render() {
return (
<div>
<OtherComponent1 someArrayProp={this.state.data}/>
<OtherComponent2 differentArrayProp={this.state.data}/>
</div>
);
}
}
export default App;
import React, {Component} from 'react';
import PropTypes from 'prop-types';
class OtherComponent1 extends Component {
render() {
return (
<div>
The someArrayProp: {this.props.someArrayProp}
</div>
);
}
}
OtherComponent1.propTypes = {
someArrayProp: PropTypes.array;
}
export default App;
import React, {Component} from 'react';
import PropTypes from 'prop-types';
const OtherComponent2 = (props) => (
<div>
The differentArrayProp: {props.differentArrayProp}
</div>
);
OtherComponent2.propTypes = {
differentArrayProp: PropTypes.array;
}
export default App;