我试图用ReactJs发出的API请求的响应进行分页。我有一个 Main.js 页面,用于将道具发送到子组件 PageButtons.js 。一切顺利,我通过控制台检查了我传递的值的this.props。
问题是我需要更新道具的状态,并且需要在 parent 组件(即Main.js)上进行更新。我使用它来增加获取API请求的限制和偏移量的值,具体取决于我刚刚单击的按钮,但这不会发生... :(
这个问题还有更多细节,例如获取响应的数组(Client-side pagination of API fetch only with ReactJs)。
我将在此处保留Main.js代码(不包括导入):
export class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
models: [],
offset: offset,
limit: limit
};
}
componentDidMount() {
/* here is other two fetches that ask for a token */
fetch(url + '/couch-model/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
models: json.results
}, () => {});
})
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Estamos a preparar o seu sofá!
</div>
)
} else {
return (
<div>
{models.map(model =>
<a href={"/sofa?id=" + model.id} key={model.id}>
<div className="Parcelas">
<img src={model.image} className="ParcImage" alt="sofa" />
<h1>Sofá {model.name}</h1>
<p className="Features">{model.brand.name}</p>
<button className="Botao">
<p className="MostraDepois">Ver Detalhes</p>
<span>+</span>
</button>
<img src="../../img/points.svg" className="Decoration" alt="points" />
</div>
</a>
)}
<PageButtons limit={limit} offset={offset}/>
</div>
)
}
}
}
现在是PageButtons.js代码:
export class PageButtons extends React.Component {
ButtonOne = () => {
let limit = 9;
let offset = 0;
this.setState({
limit: limit,
offset: offset
});
};
ButtonTwo = () => {
this.setState({
limit: this.props.limit + 9,
offset: this.props.offset + 9
});
};
render() {
console.log('props: ', this.props.limit + ', ' + this.props.offset);
return (
<div id="PageButtons">
<button onClick={this.ButtonOne}>1</button>
<button onClick={this.ButtonTwo}>2</button>
<button>3</button>
<button>></button>
</div>
)
}
}
答案 0 :(得分:1)
将以下方法添加到Main.js
fetchRecords = (limit, offset) => {
// fetch call code goes here and update your state of data here
}
handleFirstButton = (limit, offset) => {
this.setState({limit : limit, offset: offset})
this.fetchRecords(limit, offset)
}
handleSecondButton = (limit, offset) => {
this.setState({limit: limit, offset : offset})
this.fetchRecords(limit, offset)
}
Main.js渲染方法更改:
<PageButtons
limit={limit}
offset={offset}
handleFirstButton={this.handleFirstButton}
handleSecondButton={this.handleSecondButton}/>
PageButtons.js更改。
ButtonOne = () => {
let limit = 9;
let offset = 0;
this.props.handleFirstButton(limit, offset);
};
ButtonTwo = () => {
let {limit, offset} = this.props;
limit += 9;
offset += 9;
this.props.handleSecondButton(limit, offset);
};