import {UPDATE_USER} from '../actions/index';
const DEFAULT_STATE = {
createdAt:"",
name:"",
email:"",
password:"",
skill:"",
goal:"",
step1:"",
step2:"",
step3:"",
step4:"",
step5:"",
posts:[],
completed:0
}
export default function(state = DEFAULT_STATE, action) {
if (action.error) {
action.type = 'HANDLE_ERROR'; // change the type
}
switch (action.type) {
case UPDATE_USER:
console.log(action.payload)
return {
createdAt:action.payload.createdAt,
name:action.payload.name,
email:action.payload.email,
password:action.payload.password,
goal:action.payload.goal,
skill:action.payload.skill,
step1:action.payload.step1,
step2:action.payload.step2,
step3:action.payload.step3,
step4:action.payload.step4,
step5:action.payload.step5,
completed:action.payload.completed,
}
React没有检测到道具变化。我很确定答案在于我改变减速器参数(来自研究问题)。有谁知道我会如何重组以不变异?
编辑-my react类片段如下。我的地图发送到道具是在底部。用户登录到应用程序会被重定向到此页面,我在componentwillMount()中从redux设置本地页面状态。然后我有一个调用api和更新redux的函数。 React应该看到这个变化,因为道具已经改变了?或者我是否必须在componentWillRecieveProps()中手动设置状态?
class YourPage extends React.Component {
constructor(props) {
super(props);
this.state = {
post:"",
date:"",
email:"",
completed:0,
posted:true,
timeSincePost:"",
lastPost:""
}
this.handleInputChange = this.handleInputChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
const mapStateToProps = (state) =>({
name:state.user.name,
email:state.user.email,
completed:state.user.completed,
})
const mapDispatchToProps = (dispatch) => ({
callApi: (value, state) => {
var obj = {
date:moment.tz(moment.tz.guess()).format(),
post:state.post,
email:state.email,
completed:(parseFloat(state.completed) + .75),
}
API.addPost(obj)
.then(function(res){
dispatch(updateUser(res.data))
})
}
})
export default connect(mapStateToProps,mapDispatchToProps)(YourPage);
答案 0 :(得分:0)
使用Object.assign
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
import { UPDATE_USER } from '../actions/index';
const DEFAULT_STATE = {
createdAt: "",
name: "",
email: "",
password: "",
skill: "",
goal: "",
step1: "",
step2: "",
step3: "",
step4: "",
step5: "",
posts: [],
completed: 0
}
export default function (state = DEFAULT_STATE, action) {
if (action.error) {
action.type = 'HANDLE_ERROR'; // change the type
}
switch (action.type) {
case UPDATE_USER:
console.log(action.payload)
return Object.assign({}, state, {
createdAt: action.payload.createdAt,
name: action.payload.name,
email: action.payload.email,
password: action.payload.password,
goal: action.payload.goal,
skill: action.payload.skill,
step1: action.payload.step1,
step2: action.payload.step2,
step3: action.payload.step3,
step4: action.payload.step4,
step5: action.payload.step5,
completed: action.payload.completed,
});