我在自学项目中使用了一些不同的技术(reddit clone):
目标:点击帖子的修改链接时,请转到正确的路线,并填充编辑表单字段。
我正在使用一个容器来调度一个动作并重新渲染更新容器道具内的组件。它看起来像这样:
CONTAINER:
class PostContainer extends Component {
componentDidMount() {
debugger;
const {id} = this.props.match.params;
this.props.dispatch(fetchPost(id));
}
render() {
return (
<Post post={this.props.post} editing={this.props.location.state? this.props.location.state.editing : false}/>
);
}
}
const mapStateToProps = (state, ownProps) => {
debugger;
return {
...ownProps,
post: state.post
};
};
export default connect(mapStateToProps)(withRouter(PostContainer));
嵌套的Post组件具有其他嵌套组件:
POST组件:
class Post extends Component {
constructor(props) {
super(props);
this.editToggle = this.editToggle.bind(this);
}
state = {
editing: this.props.location.state ? this.props.location.state.editing : false
};
editToggle() {
this.setState({editing: !this.state.editing});
}
render() {
const {editing} = this.state;
if (editing || this.props.post === undefined) {
return <PostEditForm editToggle={this.editToggle} editing={this.props.editing} post={this.props.post || {}}/>;
}
return (
<div>
<div>
<h2>Title: {this.props.post.title}</h2>
<span>Author: {this.props.post.author}</span>
<br/>
<span>Posted: {distanceInWordsToNow(this.props.post.timestamp)} ago f</span>
<p>Body: {this.props.post.body}</p>
<button type='button' className='btn btn-primary' onClick={() => this.editToggle()}>Make Edit</button>
</div>
<hr/>
<Comments post={this.props.post}></Comments>
</div>
);
}
}
export default withRouter(Post);
在第一个render
语句中的if
函数中,我将更新的道具传递给<PostEditForm>
。当PostEditForm收到道具时,它会重新渲染组件,但组件的状态不会更新。
PostEditForm:
class PostEditForm extends Component {
state = {
timestamp: this.props.post.timestamp || Date.now(),
editing: this.props.editing || false,
body: this.props.post.body || '',
title: this.props.post.title || '',
category: this.props.post.category || '',
author: this.props.post.author || '',
id: this.props.post.id || uuid()
};
clearFormInfo = () => {
this.setState({
timestamp: Date.now(),
body: '',
title: '',
category: '',
author: '',
id: uuid(),
editing: false
});
};
handleOnChange = (e) => {
this.setState({[e.target.id]: e.target.value});
};
handleSubmit = event => {
event.preventDefault();
const post = {
...this.state
};
if(this.state.editing) {
this.props.dispatch(updatePostAPI(post));
this.setState({
editing: false
})
} else {
this.props.dispatch(createPostAPI(post));
this.clearFormInfo();
window.location.href = `/${post.category}/${post.id}`;
}
};
render() {
const {editing} = this.state;
return (
<form onSubmit={this.handleSubmit}>
<div>
<h2>Create New Post</h2>
<label htmlFor='text'>
Title:
<input
type="text"
onChange={this.handleOnChange}
value={this.state.title}
placeholder="Enter Title"
required
id="title"
name="title"
/>
</label>
<label>
Author:
<input
type="text"
onChange={this.handleOnChange}
value={this.state.author}
placeholder="Enter Author"
required
id="author"
name="author"
/>
</label>
<label>
</label>
<label>
Body:
<textarea
type="text"
onChange={this.handleOnChange}
value={this.state.body}
placeholder="Enter Body"
required
id="body"
name="body"
/>
</label>
</div>
<label>
Category:
<select id = 'category' onChange={this.handleOnChange} value={this.state.value} required>
<option value='Select Category'>Select Category</option>
<option value='react'>react</option>
<option value='redux'>redux</option>
<option value='udacity'>udacity</option>
</select>
</label>
<button type='submit'>Create Post</button>
</form>
);
}
}
export default connect()(PostEditForm);
我相信我需要调用setState
并分配传递给状态的新道具,但我不知道要使用哪个lifeCycle方法。
当我使用componentDidUpdate
时,类似于:
class PostEditForm extends Component {
componentDidUpdate(prevProps) {
if(this.props.post.id !== prevProps.post.id) {
this.setState({
timestamp: this.props.post.timestamp,
editing: this.props.post.editing,
title: this.props.post.title,
category: this.props.post.category,
author: this.props.post.author,
id: this.props.post.id
})
}
}
.....
componentDidUpdate
解决了最初的问题,但每当我更新我正在编辑的表单中的内容时,都会调用lifeclycle方法,不需要onChange处理程序,这是一个很好的做法,还是应该使用不同的接近?
答案 0 :(得分:1)
只是一个注释
每次重新渲染后都会调用 componentDidUdpate
componentDidMount
。
如果你在componentDidUdpate()
钩子内修改你的状态,你将会以无限循环结束,因为setState()
将重新触发render()
,因此componentDidUpdate()
如果你在componentDidMount()
中修改你的状态,那么这个钩子只被调用一次,在实例化之后,并不是每次重新渲染都会因此对后续更新不起作用。
然而问题出现在这里:
state = {
timestamp: this.props.post.timestamp || Date.now(),
editing: this.props.editing || false,
body: this.props.post.body || '',
title: this.props.post.title || '',
category: this.props.post.category || '',
author: this.props.post.author || '',
id: this.props.post.id || uuid()
};
render() {
const {editing} = this.state;
//change to const {editing} = this.props;
....
}
你声明状态的方式不适用于将来的更新,一旦完成实例,状态将指向道具的值,只是原始值不可变的定义。
您应该在整个this.props
PostEditForm
方法而不是render()
中引用this.state
,您应该没问题。
更新状态,你应该从父代(在这种情况下是Post组件)中将回调传递给PostEditForm并在需要时触发它。
关于默认值,我建议使用Proptypes库。
类似的东西:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
class PostEditForm extends Component {
//your business logic
}
PostEditForm.propTypes = {
timestamp: Proptypes.Object,
editing: PropTypes.bool,
body: PropTypes.string,
title: PropTypes.string,
category: PropTypes.string,
author: PropTypes.string,
id: PropTypes.string
}
PostEditForm.defaultProps = {
timestamp: Date.now(),
editing: false,
body: '',
title: '',
category: '',
author: '',
id: uuid()
}