React Redux调度操作和读取状态



试图通过将第一个文本框的值传递给第二个文本框来理解redux概念。

//文件1-类别组件

import React, { Component } from 'react';
import { actionCreators } from '../store/CustomerInvoice';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class CustomerInvoice extends Component {
constructor(props) {
super(props);
this.state = {
accountId: "",
customerName: ""
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
var name = event.target.name;
var value = event.target.value;
this.setState({ [name]: value });
this.props.accountEntered(value);
}
render() {
return (
<form>
<div className="form-group">
<label htmlFor="accountId">Account Id:</label>
<input type="text" className="form-control" name="accountId" placeholder="Account Id" value={this.state.accountId} onChange={this.handleChange} />
<small id="accountId" className="form-text text-muted">Enter customer accound Id</small>
</div>
<div className="form-group">
<label htmlFor="customerName">Customer name:</label>
<input type="text" className="form-control" name="customerName" placeholder="Customer name" value={this.test}  />
</div>

<button type="submit" className="btn btn-primary">Submit</button>
</form>
)
}
}
const mapStateToProps = state => ({
test: state.test
});
export default connect(
mapStateToProps,
dispatch => bindActionCreators(actionCreators, dispatch)
)(CustomerInvoice);

//文件2-Redux

const accountIdEntered = 'ACCOUNT_ENTERED';
const initialState = { test: "" };
export const actionCreators = {
accountEntered: (content) => ({
type: accountIdEntered,
payload: {
content
}
})
}
export const reducer = (state, action) => {
state = state || initialState;
if (action.type === accountIdEntered) {
return { ...state, test: action.content };
}
return state;
}

不确定问题在哪里。请帮我解决这个问题。基本上,我想实际理解redux的概念,在这里我可以调度一个操作,修改一些值,并从存储中读取值。

首先,如果您检查您的操作accountEntered在有效载荷内返回content

accountEntered: (content) => ({
type: accountIdEntered,
payload: {
content
}
})

因此,当您在reducer中调度操作时,您需要正确地从操作中获取数据,即action.payload.content:

export const reducer = (state, action) => {
state = state || initialState;
if (action.type === accountIdEntered) {
return { ...state, test: action.payload.content };
}
return state;
}

此外,您还可以安装Redux Dev工具chrome扩展,用于可视化何时调度操作以及减速器状态如何变化等。

相关内容

  • 没有找到相关文章

最新更新