我正在尝试将输入标记值更新为redux-reducer。
这是我的代码:
我的行动已创建:
export const addName = text => ({
type:'Add Name',
text
})
我的减速器组件是:
export default function() {
return { firstName: " "}
}
我的最终index.js是:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import rootReducer from "./reducers/name";
import { createStore } from "redux";
import { Provider } from "react-redux";
import registerServiceWorker from './registerServiceWorker';
let store = createStore(rootReducer)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
registerServiceWorker();
我的表现形式是:
import React,{Component} from "react";
import { connect } from "react-redux";
import { addName } from "./actions";
class App extends Component {
inputData = (event) =>
{
this.setState({
[event.target.name]:event.target.value
});
}
submitData = (event) =>
{
event.preventDefault();
console.log(this.props.firstName)
dispatch(addName(this.input.value))
}
render(){
return(
<div>
<form>
FirstName:
<input type="text" name={this.props.firstName} onChange={this.inputData}/>
<button type="submit">Submit</button>
</form>
{this.props.firstName}
</div>
);
}
}
function mapStateToProps(dispatch)
{
return{
firstName: state.firstName
};
}
export default connect(mapStateToProps)(App);
我只想从输入字段中获取值,然后在onSubmit按钮上我想更新reducer firstName以进行更新... 请帮助解决这个问题.......
我关注了redux todo应用程序示例,但无法进行任何连接....
答案 0 :(得分:0)
您可能在控制台中收到有关dispatch
方法的错误。
在submitData
方法更改
dispatch(addName(this.input.value))
到
this.props.dispatch(addName(this.input.value))
编辑:
在mapStateToProps
函数中,您期望dispatch
,并且在定义中您正在访问state.firstName
。将参数更改为state
,如下所示:
function mapStateToProps(state)
{
return{
firstName: state.firstName
};
}
答案 1 :(得分:0)
您的动作创建者应如下所示:
export const setName = action => {
type: "SET_NAME",
action
}
和reducer看起来像下面的代码:
export const FormReducer = (state = initState, action) => {
switch(action.type){
case "SET_NAME":
return {...state, name: action.name}
default:
return state
}
}
并且在您的组件中,最好将操作传递给道具,如下面的代码:
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
事实上,您应该import * as action from your action creator :)
并在表单上提交以下代码:
this.props.actions.setName({name:event.target.value})