简体   繁体   English

如何有条件地呈现状态属性

[英]How to conditionally render an attribute of state

I'm trying to get a dropdown menu to display the name of the topic that a user selected from a previous page (currently, it defaults back to 'Topics'). 我正在尝试获取一个下拉菜单,以显示用户从上一页中选择的主题名称(当前,默认情况下返回“主题”)。

While I'm able to get $r.state.topics[$r.state.topicSelected].name in the console, I get an undefined error when I put this.state.topics[this.state.topicSelected].name in my code. 虽然我可以在控制台中获取$r.state.topics[$r.state.topicSelected].name ,但将this.state.topics[this.state.topicSelected].name放入this.state.topics[this.state.topicSelected].name出现了未定义的错误。我的代码。

So, I'm trying to use conditional rendering to have 'Topics' render as a default while the topics themselves are gathered with a fetch request. 因此,我尝试使用条件渲染将“主题”渲染作为默认渲染,而主题本身是通过访存请求收集的。

<select
value={this.state.topicSelected}
onChange={this.onTopicClick}
className="sort"
data-element>
    {
    // Add this option in the .then() when populating siteCategories()
    [<option key={this.state.topicSelected}
      value={this.state.topicSelected}>({if 
       (this.state.topics[this.state.topicSelected].name == undefined) {
       'Topics'
    } else {
    this.state.topics[this.state.topicSelected].name
     }})
    </option>].concat(
this.state.topics.map(function (topic) {
 return (<option
 key={topic.id}
 value={topic.id}>{topic.name}</option>);
  }))
 }
</select>

I'm getting a unexpected token error, but I've tried various combinations of syntaxes with no luck - how do I properly run this conditional formatting? 我遇到了意外的令牌错误,但是我尝试了各种语法组合,但都没有碰到运气-如何正确运行这种条件格式?

You can use a ternary expression ? : 您可以使用三元表达式? : ? : . ? : Like so, 像这样

this.state.topics[this.state.topicSelected] ? this.state.topics[this.state.topicSelected].name : 'Topics'

Since undefined is a falsy value, it will return 'Topics' when this.state.topics[this.state.topicSelected] is undefined. 由于undefined是虚假值,因此当this.state.topics[this.state.topicSelected]未定义时,它将返回“ Topics”。

<select
  value={this.state.topicSelected}
  onChange={this.onTopicClick}
  className="sort"
  data-element>
      <option key={this.state.topicSelected}
        value={this.state.topicSelected}>
        {this.state.topics[this.state.topicSelected] ?
         this.state.topics[this.state.topicSelected].name : 'Topics'}
      </option>
      {this.state.topics.map(function (topic) {
         return (<option key={topic.id} value={topic.id}>{topic.name}</option>);
      })}
</select>

With the way you have done things, there are some other problems as well, but I didn't see them as relevant to your question. 在您做事的方式上,还存在其他一些问题,但是我认为它们与您的问题无关。 For one, you are changing the first option of the list to be your selected value. 例如,您正在将列表的第一个选项更改为所选值。 Instead, you should be setting the value of the select which automatically selects the correct option from the list. 相反,您应该设置select的值,该值会自动从列表中选择正确的选项。 Here's how I would write this: 这是我的写法:

render() {
<select
  value={this.state.topicSelected}
  onChange={this.onTopicClick}
  className="sort"
  data-element>
      <option value={0}>Topics</option>
      {this.state.topics.map(topic => 
             <option key={topic.id} value={topic.id}>{topic.name}</option>))}
</select>
}

You can also make it a controlled component and default the state as follows 您还可以使其成为受控组件并按如下所示默认状态

function App() {
  const [topics] = useState(["Math", "Geography"]);
  const [selectedTopic, setSelected] = useState("Topic");
  return (
    <select
      value={selectedTopic}
      onChange={(e) => setSelected(e.target.value)}
      className="sort"
    >
      <option>
        Topic
      </option>
      {topics.map(topic => (
        <option key={topic} value={topic}>
          {topic}
        </option>
      ))}
    </select>
  );
}

Class Version of the component 组件的类版本

class App extends React.Component {
  state = {
    topics: ["Math", "Geography"],
    selectedTopic: "Topic",
  }

  render() {
    const { selectedTopic, topics } = this.state;
    return (
      <select
      value={selectedTopic}
      onChange={(e) => this.setState({ selectedTopic: e.target.value })}
      className="sort"
      >
      <option>
        Topic
      </option>
      {topics.map(topic => (
        <option key={topic} value={topic}>
          {topic}
        </option>
      ))}
    </select>
    );
  }
}

Also in your render method you cannot have an if statement as only javascript expressions are allowed in there. 另外,在您的render方法中,您不能包含if语句,因为其中仅允许javascript表达式。 If you need to use conditional statements either use the ternary operator or create a function with the if blocks, that can be called from render. 如果需要使用条件语句,请使用三元运算符或使用if块创建函数,可以从render调用该函数。 You can read more about expressions here 您可以在此处阅读有关表达式的更多信息

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

相关问题 如何渲染相同的组件但具有初始状态(有条件地)? - How to render the same component but with initial state (conditionally)? 如何在 React 中有条件地渲染 JSON 属性 - 如果属性存在则渲染 - How to render JSON attributes conditionally in React - Render if the attribute exists 在 React 中,如果 state 是一个空数组,那么如何有条件地呈现文本? - In React, if a state is an empty array then how do you render a text conditionally? 如何在useEffect中更新状态的react组件中有条件地呈现? - How to conditionally render in a react component with state updated in useEffect? react中如何根据props有条件地渲染数据属性 - How to conditionally render a data attribute based on props in react 反应:如何有条件地渲染? - React: How to conditionally render? 如何有条件地渲染组件? - How to render a component conditionally? 使用单选按钮 React 设置 state 以有条件地渲染 - Set state with radio buttons, React, to render conditionally 在 JSX 文本中有条件地呈现日期 state 变量 - Conditionally render date state variable in JSX Text 如何使用反应钩子在全局状态的叶值发生变化时有条件地渲染组件 - How to render component conditionally when leaf value of global state changes using react hooks
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM