我有 App.js -
import './App.css';
import { connect } from 'react-redux'
import { ActionChangeName } from "./Actions/Action";
function App(props) {
return (
<div className="App">
<div>
Name
<input id="txtName" type="text"></input>
</div>
<div>
Age
<input id="txtAge" type="text"></input>
</div>
<div>
<button onClick={()=>{props.ActionChangeName("Suresh")}}>Change</button>
</div>
My Name is {props.name}.
I am {props.age} Years Old !
</div>
);
}
const mapToProp=(state)=>{
return{
...state,
name:"Sagar",
age:"22"
}
}
const mapToDispatch=(dispatch)=>{
return {
ActionChangeName:(name)=>{
dispatch(ActionChangeName(name));
}
}
}
export default connect(mapToProp,mapToDispatch)(App) ;
Reducer.js -
const iState={
name :"sagar",
age:"22"
}
export const reducer=(state=iState,action)=>{
alert(action.payload);
return {
...state,
name:action.payload
}
}
Action.js -
import React from 'react'
export function ActionChangeName(name) {
return {
type:"CHANGE_NAME",
payload :name
}
}
当我通过调度函数发送“Suresh”时,我可以看到它通过警报到达我的减速器。 但我希望 App.js 中的标签值更新为 -
我叫苏雷什。
我可以看到它剩余 - 我的名字是 Sagar ,这是初始状态。
答案 0 :(得分:2)
看起来您确实在 mapStateToProp
函数中再次覆盖了您的姓名和年龄,该函数中只应返回状态:
const mapToProp = (state) => {
return {
...state,
// you would nee to remove this overrides
// name: "Sagar",
// age: "22"
}
}
答案 1 :(得分:0)
随着@tmhao2005 的回答的更新,我更新了 -
const mapToProp=(state)=>{
return{
...state,
name:state.name==null?"Sagar":state.name
//age:"22"
}
}
这开始起作用了。 所有功劳都归功于 @tmhao2005 ,因为如果没有他最初的回答,就不会达到这一点。