具有一个纯响应组件,该组件在redux存储更改时会更新...所有对象都是不可变的...我的存储库中有一个不可变的地图作为我的根,还有一个图书地图(以地图形式)。更新启动时,我的道具值更改为正确,但我的状态值不...
由于比较浅,我认为是这样,但我想问专家他们会怎么做。他们认为正在发生什么。...
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import _bookDetails from './_bookDetails'
import { withRouter } from 'react-router-dom';
import BookForm, {PERSPECTIVE} from './BookForm'
import * as bookActions from "../../actions/bookActions";
class BookDetailsPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
showUpdateForm: false,
book: this.props.book,
date: this.props.date
};
this.toggleUpdate = this.toggleUpdate.bind(this);
}
render() {
console.log(this.state.book);
console.log(this.props.book);
...
}
// Map state to props
const mapStateToProps = (state, ownProps) => {
let allBooks = state.get('books');
let book = state.get('book');
try{
book = allBooks.get(book.get('id'));
} catch(err){
console.warn('empty book object');
}
return {
book: book,
date: new Date()
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchBookById: bookId => dispatch(bookActions.fetchBookById(bookId))
};
};
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(BookDetailsPage)
);
答案 0 :(得分:0)
这是因为您仅将this.state.book
绑定到this.props.book
一次(在构造函数中)。首次安装该组件时,构造函数只会被调用一次 。您需要的是在componentDidUpdate
更新时使用this.state.book
来更新this.props.book
:
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import _bookDetails from './_bookDetails'
import { withRouter } from 'react-router-dom';
import BookForm, {PERSPECTIVE} from './BookForm'
import * as bookActions from "../../actions/bookActions";
class BookDetailsPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
showUpdateForm: false,
book: this.props.book,
date: this.props.date
};
this.toggleUpdate = this.toggleUpdate.bind(this);
}
componentDidUpdate(prevProps, prevState) {
// Make sure your book prop is different
if(prevProps.book !== this.props.book) {
// Update state with new book value
this.setState({
book: this.props.book
});
}
}
render() {
console.log(this.state.book);
console.log(this.props.book);
...
}
// Map state to props
const mapStateToProps = (state, ownProps) => {
let allBooks = state.get('books');
let book = state.get('book');
try{
book = allBooks.get(book.get('id'));
} catch(err){
console.warn('empty book object');
}
return {
book: book,
date: new Date()
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchBookById: bookId => dispatch(bookActions.fetchBookById(bookId))
};
};
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(BookDetailsPage)
);