我想做一件简单的事情:我有一个带有3个输入的reducer,我想改变点击输入的值,即更改商店中属性的值 。我该怎么做 ?
我正在使用 React和Redux 。
这里是我的reducer-inputs.js:
export default function (){
return[
{
"name":"InputOne",
"deviceType":"Input",
"value":"42",
"description":"This is the first Input"
},
{
"name":"InputTwo",
"deviceType":"Input",
"value":"21",
"description":"This is the second Input"
},
{
"name":"InputThree",
"deviceType":"Input",
"value":"13",
"description":"This is the third Input"
}
]
}
然后,我把减速机放在我的商店里。
我点击事件的组件元素:
<td className="sendButton" onClick={() => this.props.changeButtonValue(this.props.activeDevice.name,this.refs.buttonConfig.value)}> Send </td>
我创建了一个动作:
export const changeInputValue = (name,val) => {
console.log(name + ":" + val);
return {
type: "INPUT_CHANGE",
payload: {name,val}
}
};
在这里,我正在努力改变输入的价值......
export default function (state={},action){
switch(action.type){
case "INPUT_CHANGE":
console.log(action.payload);
// shows the name of the input and the new value wanted
console.log(action.payload.name);
console.log(state)
// shows the element in the reducer I feel like changing
return {
...state,
value: action.payload.val
// some code Here ....
}
break;
default:
return state;
}
return state;
}
这是我的输入字段:
import React, { Component } from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {changeInputValue} from '../Actions/index';
class DeviceConfig extends Component {
render() {
switch(this.props.activeDevice.deviceType){
case "Input":
return (
<div>
<table>
<tbody>
<tr>
<td className="selected_DeviceName"> {this.props.activeDevice.name} </td>
<td> <input type="number" ref="inputConfig" defaultValue="" /> </td>
<td className="sendButton" onClick={() => this.props.changeInputValue(this.props.activeDevice.name,this.refs.inputConfig.value)}> Send </td>
</tr>
</tbody>
</table>
</div>
);
default:
return (
<p> Select a Device </p>
);
}
}
}
function mapStateToProps(state){
return{
activeDevice:state.activeDevice,
};
}
function matchDispatchToProps (dispatch) {
return bindActionCreators({changeInputValue: changeInputValue}, dispatch)
}
// Link between store and container
export default connect(mapStateToProps,matchDispatchToProps)(DeviceConfig);
提前谢谢!