我是 javascript 的新手,我想运行一些代码,具体取决于 state.value != null 或“”。它不会引发错误,但会卡住在那里。请在下面查看我的代码。非常感谢任何帮助。
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>
);
}
最佳答案
评估字符串的存在
在 JavaScript 中:空 Strings
''
是 falsey
(评估为 false
)。
const x = ''
if (x) console.log('x = true')
else console.log('x = false')
因此,this.state.value
的存在被简洁地验证如下:
if (this.state.value) .. // Do something if this.state.value != ''
可以通过简单地引用 variables
来利用和链接此策略其次是 &&
(结果只有最后一个 truthy
变量是 returned
)。如果没有 truthy
找到变量:false
是returned
. IE。在 onClick
的情况下<button/>
的方法下面的标签。
渲染列表
在 React 中:通常存储 plain
的列表variables
( Strings
、 Objects
等)并处理到 element
的转换即时形成。
呈现 Strings
代表HTML elements
是一个安全漏洞。在生产中:有人可以很容易地输入恶意的 todo
并毁掉你的整个应用程序。您可能需要使用 dangerouslySetInnerHTML
如果你想继续沿着这条路走下去。
See the docs for more info on how to render lists.
示例
请参阅下面的待办事项容器的粗略示例。
// 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>
关于javascript - 如果或条件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847227/