[英]Trigger onChange when setting State in componentDidMount?
I need to add some query paramaters to my url as a person checks off checkboxes. 当一个人选中复选框时,我需要向我的URL添加一些查询参数。
I am using react router so I do something like this in my checkboxes on change event. 我正在使用React Router,所以我在更改事件的复选框中执行了类似的操作。
const stringified = queryString.stringify(parsed);
const path = `${this.props.location.pathname}?${stringified}`;
this.props.history.replace(path)
This does however seem to cause a re-render of the page(not sure if this should be happening, would prefer it not to do that so maybe I got to use something other than replace?). 但是,这似乎确实导致了页面的重新渲染(不确定是否应该发生这种情况,希望它不要这样做,所以也许我必须使用除replace之外的其他东西?)。
I wanted to check on componentDidMount the url to see if the value is there. 我想检查URL的componentDidMount来查看值是否存在。 If it is there then I wanted to update the state of the checkbox.
如果它在那里,那么我想更新复选框的状态。
@observable
isChecked = false;
@action
componentDidMount() {
const parsed = queryString.parse(this.props.location.search);
this.isChecked = parsed && parsed["param"] === this.props.option;
}
However I don't see the onChange being trigger. 但是我看不到onChange被触发。
Right now I have on change a function that takes the value and uses it to filter, so I need the function to run. 现在,我需要更改一个使用该值并使用它进行过滤的函数,因此我需要运行该函数。
I could put that function in the componentDidMount but I wanted to make sure before I do that, there is nothing I am missing on why the change event is not be fired. 我可以将该函数放在componentDidMount中,但我想确保在执行此操作之前,我没有丢失为何未触发change事件的信息。
Try setting the state in the constructor()
and in componentDidUpdate()
. 尝试在
constructor()
和componentDidUpdate()
设置状态。
When a URL parameter is added to the same route, the existing component is utilized (ie an update event) vs. a new one being created. 将URL参数添加到同一路由时,将利用现有组件(即更新事件)与正在创建的新组件。 As a result, you won't see a
componentDidMount()
event. 结果,您将不会看到
componentDidMount()
事件。
Another option/solution is to update the state of isChecked
directly and push the history/url change. 另一个选项/解决方案是直接更新
isChecked
的状态并推送历史记录/ URL更改。
If what you are trying to prevent is the page refresh use this built in function in your onSubmit event(if I understand your question correctly.) 如果您要阻止页面刷新,请在onSubmit事件中使用此内置函数(如果我正确理解了您的问题)。
event.preventDefault();
It stops the browser from auto-refreshing! 它阻止浏览器自动刷新! Make sure to call event in your function though.
确保在函数中调用事件。 ie
即
onSubmit=(event)=>{
event.preventDefault();
//rest of code
}
If you are trying to filter, the es6 .filter method is useful for checkboxes. 如果您尝试过滤,则es6 .filter方法对于复选框很有用。 I personally used a select dropdown menu to filter the options and selectively show the ticked items in a ToDo List: "Done" "Active" "Completed" and used those states in my filter method.
我个人使用选择下拉菜单来过滤选项,并在待办事项列表中有选择地显示被选中的项目:“完成”,“活动”,“已完成”,并在我的过滤方法中使用了这些状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.