Reactjs 是否将本地状态值指定给redux状态值?
我想将本地状态值分配给redux状态值,当我编写console.logaction以了解天气操作是否正在获取我的值时,它显示它正在获取我的值,但redux状态没有分配这些值!请给出解决方案 App.js:Reactjs 是否将本地状态值指定给redux状态值?,reactjs,redux,Reactjs,Redux,我想将本地状态值分配给redux状态值,当我编写console.logaction以了解天气操作是否正在获取我的值时,它显示它正在获取我的值,但redux状态没有分配这些值!请给出解决方案 App.js: import React,{Component} from "react"; import {connect} from "react-redux"; import {bindActionCreators} from "redux"; import {addName} from './acti
import React,{Component} from "react";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {addName} from './action';
class App extends Component {
constructor(props){
super(props);
this.state = {
first:''
};
}
inputData = event => {
this.setState({
first:event.target.value
});
}
submitData = event => {
event.preventDefault();
this.props.addName({
firstName:this.state.first
});
console.log(this.props.firstName)
}
render(){
return(
<div>
<form onSubmit={this.submitData}>
<input type="text" name="first" onChange={this.inputData}/>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
function mapStateToProps(state){
return {
firstName : state.firstName
};
};
function mapDispatchToProps(dispatch) {
return{
addName: bindActionCreators(addName,dispatch)
};
};
export default connect(mapStateToProps,mapDispatchToProps)(App)
我的动作组件index.js
export const addName = action => {
return{
type:'ADD_ENTRY',
...action
};
};
请检查当我尝试使用action.firstName分配时,我认为分配没有完成,因此请正确检查我的减速机 这是因为您没有更新reducer状态,您只是返回从操作传递给reducer的值。相反,您需要首先更新state.firstName,然后返回整个reducer状态: 编辑:
您的mapStateToProps看起来也不对。您可以发布在mapStateToProps中获得的状态值吗?我正在发布沙盒链接,请验证它…..沙盒不工作,您缺少操作。@NehaDobia在这里修复了它:。在减速器中,不能改变状态。您需要返回一个新的state副本。当我执行conole.logthis.props.firstName时,您能看到它没有在控制台中显示该值吗?
const init = {firstName: ''};
export let rootReducer = (state=init,action) => {
switch(action.type)
{
case 'ADD_ENTRY':
{
return{
firstName:action.firstName
};
}
default:
{
return state;
}
}
}
export const addName = action => {
return{
type:'ADD_ENTRY',
...action
};
};
const init = {firstName: ''};
export let rootReducer = (state=init,action) => {
switch(action.type)
{
case 'ADD_ENTRY':
{
return {...state, firstName: action.firstName }
}
default:
{
return state;
}
}
}