简体   繁体   English

React.js国家问题

[英]React.js State Issue

I have the below jsfiddle I am trying to filter the records so when once category is selected I only want to show results for that category. 我有以下jsfiddle我试图过滤记录,所以当选择一个类别我只想显示该类别的结果。 Not sure what I am missing with states. 不确定我在州里缺少什么。

https://jsfiddle.net/kkhwabzr/ https://jsfiddle.net/kkhwabzr/

var App = React.createClass({
    render: function() {
        return (
        <div>
            <Instructions />
            <h1>Requests</h1>
        </div>
        );
    }
});

You need to monitor the selection state from the main App component. 您需要从主App组件中监视选择状态。 Right now you're keeping track of the selection in the MySelect component. 现在,您将跟踪MySelect组件中的选择。 That means the App component doesn't have that information and cannot pass it to the DisplayRecords component as a prop. 这意味着App组件没有该信息,也无法将其作为prop传递给DisplayRecords组件。

The correct way to do it is keep the selection as a state variable in the App component, and pass both its value and the onChange handler as props to the MySelect component: 正确的方法是将选择保持为App组件中的状态变量,并将其值和onChange处理程序作为props传递给MySelect组件:

getInitialState: function() {
    return { selected: "All Requests" }
},

onChange:function(e){
    this.setState({selected: e.target.value})
},

render: function() {
    return (...
        <MySelect selected={this.state.selected} onChange={this.onChange} />
        <DisplayRecords records={this.props.data.filter(this.filterRecord)}
    ...)
}

As pointed out before, you can use a filter to get the correct records, but you should also account for the "all requests" case where you want to return all the records, hence: 如前所述,您可以使用过滤器来获取正确的记录,但是您还应该考虑要返回所有记录的“所有请求”情况,因此:

filterRecord: function(record) {
  if(this.state.selected === null) return true;
  return (record.status === this.state.selected || this.state.selected === "All Requests");
}

See the jsfiddle for a working example of your code: https://jsfiddle.net/kkhwabzr/3/ 有关代码的工作示例,请参阅jsfiddle: https ://jsfiddle.net/kkhwabzr/3/

I've modified it as little as possible so you can understand how the code was changed between yours and the working version. 我尽可能少地修改它,这样你就可以理解你的代码和工作版本之间的代码是如何改变的。 Note that I also added the tags as recommended when using React ( Removing row from table results in TypeError ) and changed the {value: ...} values to be consistent between the record.status and the component state. 请注意,我还在使用React时添加了标记( 从表中删除行导致TypeError ),并将{value:...}值更改为record.status和组件状态之间的一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM