目的是通过服务器响应创建一个表。
响应代码(它给出一个数组):
function Parse() {
var store;
var request = 'http://localhost:3001/Products?city=0&shop=0';
axios.get(request)
.then(function(response) {
store = response.data;
return store; // <--- Q1
})
.catch(function (error) {
() => { cl("Server Error: ", error) };
});
}
现在我需要创建一个表:
class ProductsTable extends React.Component {
constructor(props) {
super(props);
this.state = {
store: []
};
}
render() {
// this.setState({store:Parse()}) //<--- Q2
return (
<div className='ProductsTable'>
<p>{this.state.store}</p>
</div>
);
}
};
Q1-正在返回商店(项目数组)
Q2-不能在那里使用setState,因为它会循环。
需要向服务器发出请求并更新表的按钮:
class LeftPanel extends React.Component {
constructor(props) {
super(props);
this.state = {
store: []
};
}
render() {
var funct = function(elem) {
<ProductsTable />
}
return (
<div className='PanelContent Center'>
<CreateButtons funct={funct} />
</div>
);
}
};
class CreateButtons extends React.Component {
render() {
var rows = [];
rows.push(<TheButton source={source} funct={this.props.funct}/>);
return(<div className='MenuTable Center'>{rows}</div>);
}
};
class TheButton extends React.Component {
render() {
elem = <button onClick={this.props.funct}></button>;
return <div>{elem}</div>;
}
};
但我不知道如何在一个工作环境中做到这一点。 我应该在哪里放置setState,如何更新?谢谢。
我在搜索中找到了很多关于它的信息,但是我无法在我的项目中使用它 - 我对React结构没有足够的了解。
答案 0 :(得分:0)
试试这个:
首先制作ProductsTable
和TheButton
哑组件(无状态)。将Parse()
保留为辅助函数,但将其重命名为fetchData()
。
function fetchData() {
return axios.get('http://localhost:3001/Products?city=0&shop=0')
.then(response => response.data);
.catch((err) => { cl("Server Error: ", err); throw err; });
}
class ProductsTable extends React.Component {
render() {
return (
<div className='ProductsTable'>
<p>{this.props.products}</p>
</div>
);
}
};
class TheButton extends React.Component {
render() {
return (
<div>
<button onClick={this.props.onClick} />
</div>
);
}
};
然后将控制逻辑放在父对象LeftPanel
中。
class LeftPanel extends React.Component {
constructor(props) {
super(props);
this.getData = this.getData.bind(this);
this.state = { store: [] };
}
getData() {
fetchData().then((data) => this.setState({ store: data }));
}
render() {
return (
<div className='PanelContent Center'>
<div className='MenuTable Center'>
<TheButton onClick={this.getData} />
</div>
<ProductsTable products={this.state.store} />
</div>
);
}
};
您可能需要更改一些细节以满足您的特定需求。