最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop reactjs component rerender on state change - Stack Overflow

programmeradmin4浏览0评论

I have a form with some input fields (some of them hidden until a checkbox is checked. When I check/uncheck the checkbox a specific state is set (this.state.isChecked = true/false).

On render method, i have a div (containing some input fields) with some classes and this condition for "show" class: <div className={'extra-fields ' + (this.state.isChecked? ' show' : '')}>...</div>

Expected behavior is that on state change, only the "show" class is putted or deleted from div Current behavior: the entire form is rendered again and all data written in the input fields are lost.

How it should be done this?

I have a form with some input fields (some of them hidden until a checkbox is checked. When I check/uncheck the checkbox a specific state is set (this.state.isChecked = true/false).

On render method, i have a div (containing some input fields) with some classes and this condition for "show" class: <div className={'extra-fields ' + (this.state.isChecked? ' show' : '')}>...</div>

Expected behavior is that on state change, only the "show" class is putted or deleted from div Current behavior: the entire form is rendered again and all data written in the input fields are lost.

How it should be done this?

Share Improve this question asked Feb 15, 2016 at 7:19 user5512965user5512965 1512 gold badges3 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

If the value of the input fields is important (which they apparently are), and if they can change (which the obviously can), then React should be aware of them, typically in state.
The 'standard' (on only) react way to maintain the contents of the input fields is:

  • put the content of the input fields in state as well,
  • include something like value={this.state.foo} and onChange={this._onChange()} to the render of each input field
  • include the _onChange() function to the form to handle input changes

That way, whenever the form is re-rendered (after each setState()), the input values are also preserved.

PS: The question title "stop reactjs ponent from rerender on state change" does not really cover the question from text: you are asking for a partial re-render: do re-render the show/hide extra fields based on checkbox, but do not re-render input fields.

The short answer is that you can prevent a ponent from rendering/updating with the shouldUpdateComponent life-cycle event: https://facebook.github.io/react/docs/react-ponent.html#shouldponentupdate

However, I agree with the previous answer, that for the sake of doing what sounds like a partial re-render, and to follow best practices in general, you should be storing the state of your input fields somewhere in a ponent so that they persist beyond a render call.

发布评论

评论列表(0)

  1. 暂无评论