Open gaearon opened 6 years ago
@gaearon That blog post on derived state, contains such important information I would advise to put it as a section under the official docs, and not as a blog post.
Also since we are at it, the blog post is generally well written, only the part about memoization is a little bit weak. Two points:
None of the implementations shown in this section will work if props.list is recreated each time the parent component renders. But in most cases, this setup is appropriate.
The blog post just contains above statement without giving further explanation why none of the examples would work if props.list is recreated. This doesn't seem evident to me either.
class Example extends Component { state = { filterText: "", };
// // NOTE: this example is NOT the recommended approach. // See the examples below for our recommendations instead. //
static getDerivedStateFromProps(props, state) { // Re-run the filter whenever the list array or filter text change. // Note we need to store prevPropsList and prevFilterText to detect changes. if ( props.list !== state.prevPropsList || state.prevFilterText !== state.filterText ) { return { prevPropsList: props.list, prevFilterText: state.filterText, filteredList: props.list.filter(item => item.text.includes(state.filterText)) }; } return null; }
handleChange = event => { this.setState({ filterText: event.target.value }); };
render() { return (
);
} }
isn't complete in the sense that if filterText is changed by user in `input`, the items aren't re-filtered
with new filter value, isn't it?
Would not it be better to put a full, complete example instead? and reason about that?
is this issue open for work?
https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html still contains a few recommendations to use
getDerivedStateFromProps
like:We should figure out a way to dial them down or at least direct people to the newer blog post.