简体   繁体   English

如果或条件不起作用

[英]if or condition doesn't work

I'm new to javascript and I want to run some code depending if the state.value != null or "".it doesn't throw an error but freezes there.我是 javascript 新手,我想根据 state.value != null 或 "" 运行一些代码。它不会抛出错误,但会在那里冻结。 please see my code down below.any help would be really appreciated.请在下面查看我的代码。任何帮助将不胜感激。

constructor(){
    super();
    this.state = {
        value:null,
        list:[]
    }
}

handleList = () => {
    //let list = this.state.list.slice();
    if (this.state.value != null || this.state.value.length() > 0 ) {
        let list = [...this.state.list];
        list.push(<li>{this.state.value}</li>);

        this.setState({list});
        console.log(list.length,this.state.list.length);
    }else{
        console.log("Cant enter null");
    }
}


render() {

    return(
        <div className = 'global'>

           <button onClick={() => {this.handleList()}
            }>Add-New</button>
            <input 
                onChange = {
                    (e)=>{this.setState({value: e.target.value})}
                }
                type = 'text' 
                placeholder = 'Enter New Todo!'/>
            <hr/>
            <ul>
                {
                    this.state.list.map((li) => {
                        return (li);
                    })
                }
            </ul>

        </div>
    );
}

} }

Evaluating the existence of Strings评估字符串的存在

In JavaScript: empty Strings '' are falsey (evaluate to false ).在 JavaScript 中:空Strings ''falsey (评估为false )。

 const x = '' if (x) console.log('x = true') else console.log('x = false')

As a result, the existence of this.state.value be tersely verified as follows:因此, this.state.value的存在被简洁地验证如下:

if (this.state.value) .. // Do something if this.state.value != '' 

This strategy can be leveraged and chained by simply referencing variables followed by && (which results in only the last truthy variable being returned ).可以通过简单地引用variables后跟&& (这导致仅returned最后一个truthy变量)来利用和链接此策略。 If no truthy variable is found: false is returned .如果没有找到truthy变量: returned false ie. IE。 in the case of the onClick method of the <button/> tag below.在下面的<button/>标签的onClick方法的情况下。

Rendering Lists渲染列表

In React: it is typical to store lists of plain variables ( Strings , Objects , etc) and handle conversion to element form on the fly.在 React 中:通常存储plain variables列表( StringsObjects等)并动态处理element形式的转换。

Rendering Strings representing HTML elements is a security flaw.呈现表示HTML elements Strings是一个安全漏洞。 In production: someone could very easily type a malicious todo and ruin your entire application.在生产中:有人可以很容易地输入恶意的todo并破坏你的整个应用程序。 You may need to use dangerouslySetInnerHTML if you wish to continue down that path.如果您希望继续沿着这条路走下去,您可能需要使用dangerouslySetInnerHTML SetInnerHTML。

See the docs for more info on how to render lists.有关如何呈现列表的更多信息,请参阅文档。

Example例子

See below for a rough example of a todo container.请参阅下面的 todo 容器的粗略示例。

 // Container. class Container extends React.Component { // Constructor. constructor(props) { super(props) this.state = { value: '', list: [] } } // Render. render = () => ( <div className = 'global'> <button onClick={() => this.state.value && this.setState({value: null, list: [...this.state.list, this.state.value]})}>Add</button> <input value={this.state.value} onChange={(e) => this.setState({value: event.target.value})} placeholder="Todo.."/> <hr/> <ul> {(this.state.list.length > 0 && (this.state.list.map((todo, index) => <li key={index}>{todo}</li>))) || '..'} </ul> </div> ) } // Mount. ReactDOM.render(<Container/>, document.querySelector('#root'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>

Because you are using OR, both criteria are checked.因为您使用的是 OR,所以会检查这两个条件。 So even if value is NULL, the code is still attempting to check the length of the string.因此,即使 value 为 NULL,代码仍会尝试检查字符串的长度。 But a NULL object doesn't have a "length" property, so this will result in an "value does not have property: length" error.但是 NULL 对象没有“长度”属性,因此这将导致“值没有属性:长度”错误。 To fix this, using AND ( && ) would be more appropriate.为了解决这个问题,使用 AND ( && ) 会更合适。

Additionally, the "length" property is a value, not a function, so attempting to call as function will result in an "length is function of value" error.此外,“长度”属性是一个值,而不是一个函数,因此尝试作为函数调用将导致“长度是值的函数”错误。

These errors should appear in the console when viewing your web-page.查看您的网页时,这些错误应该会出现在控制台中。 If you press F12, a window should appear at the bottom of your browser.如果按 F12,浏览器底部应该会出现一个窗口。 If you then select the console tab, you should be able to see all errors output.如果您随后选择控制台选项卡,您应该能够看到所有错误输出。 You might need to make sure you aren't filtering error messages.您可能需要确保没有过滤错误消息。

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

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