我要在仪表板上放置2个组件(用于输入值的表单和用于显示输入值的反应表组件)。当我在表单中输入值以更新Redux存储时,我可以看到来自Redux工具的更改,但是直到我转到另一个页面并返回时,表组件才更新。有人知道我在做什么错吗?
这是我的减速器。我不相信我正在这里改变状态。
减速器:
const keysReducerDefaultState = [];
export default (state = keysReducerDefaultState, action) => {
switch (action.type) {
case 'ADD_KEYS':
return [
...state,
action.keyPair
];
case 'REMOVE_KEYS':
return state.filter(({ name }) => {
return name !== action.name;
});
default:
return state;
}
}
组件1
class KeysImportForm extends React.Component {
constructor(props) {
super(props);
this.state = {
// type validation
name: "",
publicKey: "",
privateKey: "",
};
this.typeClick = this.typeClick.bind(this);
}
render() {
const { classes } = this.props;
return (
// a form that takes in 3 fields, name, publickey and privatekey
);
}
}
const mapDispatchToProps = (dispatch) => ({
addKeys: (keyPair) => dispatch(addKeys(keyPair))
});
export default withStyles(validationFormsStyle)(connect(undefined, mapDispatchToProps)(KeysImportForm));
组件2
class KeysTable extends React.Component {
constructor(props) {
super(props);
const data = props.keys.map((prop, key) => {
return {
id: key,
name: prop.name,
publicKey: prop.publicKey,
privateKey: prop.privateKey,
};
});
this.state = {
data
};
}
render() {
const { classes } = this.props;
return (
<GridContainer>
<GridItem xs={12}>
<Card>
<CardHeader color="primary" icon>
<CardIcon color="primary">
<Assignment />
</CardIcon>
<h4 className={classes.cardIconTitle}>Key Pairs</h4>
</CardHeader>
<CardBody>
<ReactTable
data={this.state.data}
filterable
columns={[
{
Header: "Name",
accessor: "name",
minWidth: 10
},
{
Header: "Public Key",
accessor: "publicKey",
minWidth: 50
},
{
Header: "Private Key",
accessor: "privateKey",
minWidth: 50
},
{
Header: "Action",
accessor: "action",
minWidth: 10,
sortable: false,
filterable: false
}
]}
defaultPageSize={10}
showPaginationTop
showPaginationBottom={false}
className="-striped -highlight"
/>
</CardBody>
</Card>
</GridItem>
</GridContainer>
);
}
}
const mapDispathToProps = (dispatch, props) => ({
removeKeys: (id) => dispatch(removeKeys(id))
});
const mapStateToProps = (state) => {
return {
keys: state.keys
}
}
export default withStyles(styles)(connect(mapStateToProps, mapDispathToProps)(KeysTable));
仪表板
class Dashboard extends React.Component {
state = {
value: 0
};
handleChange = (event, value) => {
this.setState({ value });
};
handleChangeIndex = index => {
this.setState({ value: index });
};
render() {
const { classes } = this.props;
return (
<div>
<KeysImportForm/>
<KeysTable/>
</div>
);
}
}
Dashboard.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(dashboardStyle)(Dashboard);
答案 0 :(得分:1)
我不确定100%,但是您似乎遇到以下错误:
在您的constructor
中,您会(不必要地)复制道具到您的状态,这会引入错误并破坏Redux的目的:
const data = props.keys.map((prop, key) => {
return {
id: key,
name: prop.name,
publicKey: prop.publicKey,
privateKey: prop.privateKey,
};
});
这将导致您的数据仅在调用constructor
时才更新,即在您的组件装入时(也就是您重新加载页面)。
直接将道具用作数据。每次状态更改时,Redux都会使您的组件重新呈现。