我对React还是很陌生,在这种情况下,我觉得我应该使用生命周期挂钩,但是我不确定哪个。在下面的代码中,我将调用API,并检索用户列表对象,该对象包含另一个名为members
的事物列表。像这样:
单击“取消链接”按钮后,我将状态存储为引用,并将其发布回API以取消成员链接:
import React, { Fragment } from 'react';
import FormScene from 'nwiadmin/scenes/form';
import Button from 'nwiadmin/components/button';
import { formatDate } from 'nwiadmin/utility/formatters';
import Modal from 'nwiadmin/components/modal';
import ModalActions from 'nwiadmin/components/modal/modalactions';
import SingleBusinesses from 'app/components/businesses';
let businessRef = '';
class UserBusinessSingleScene extends FormScene {
/* eslint-disable class-methods-use-this */
setInitialState(props) {
const pendingData = {
...props.data,
};
const reference = businessRef;
const isVisible = false;
this.setReferenceTarget = this.setReferenceTarget.bind(this);
return {
pendingData,
reference,
isVisible,
};
}
shouldComponentUpdate(nextProps, nextState) {
console.log('should cmp update', nextProps, nextState);
return true;
}
UNSAFE_componentWillUpdate(nextProps, nextState) {
console.log('cmp will update', nextProps, nextState);
}
componentDidUpdate(prevProps, prevState) {
console.log('cmp did update', prevProps, prevState);
}
setLabel(data) {
return data.name;
}
setMethod() {
return 'post';
}
setRemote() {
return `businesses/unclaim?reference=${this.state.reference}`;
}
modalToggleHander() {
this.setState(prevState => ({
isVisible: !prevState.isVisible,
}));
}
setReferenceTarget() {
this.setState({ reference: businessRef });
}
render() {
console.log(this.state.reference);
return (
<Fragment>
{this.state.pendingData.members.map(business => (
<SingleBusinesses
key={business.reference}
name={business.name}
reference={business.reference}
claimed={`Claimed on: ${formatDate(business.created_at)}`}
unlink={
<Button
onClick={() => {
businessRef = business.reference;
this.setReferenceTarget();
this.modalToggleHander();
}}
>
Unlink User
</Button>
}
/>
))}
<Modal isOpen={this.state.isVisible} title="Are you sure you want to unlink the user?">
<ModalActions
submit={() => this.submit()}
submitText="Unlink User"
cancel={() => this.modalToggleHander()}
/>
</Modal>
</Fragment>
);
}
}
export default UserBusinessSingleScene;
一旦取消链接,我将收到一个Uncaught TypeError: Cannot read property 'map' of undefined
错误。我不确定100%为什么,但是我觉得这与状态有关,我应该在取消链接后设置状态吗?任何帮助表示赞赏。