[英]React not re-rendering after redux update
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未檢測到道具變更。 我很確定答案就在於我變異化reducer參數(通過研究問題)。 有誰知道我將如何重組以免變異?
編輯-my react class片段在下面。 我的地圖發給道具在底部。 用戶登錄到應用程序后將重定向到此頁面,在該頁面中,我通過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);
使用Object.assign
https://developer.mozilla.org/zh-CN/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,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.