简体   繁体   English

React 16:TypeError:this.state.userInput.map不是函数

[英]React 16: TypeError: this.state.userInput.map is not a function

I have simple react app, which a user can enter a text input , I want to display character entered as list 我有简单的反应应用程序,用户可以输入文本输入,我想显示作为列表输入的字符

here is what I have done so far: 这是我到目前为止所做的:

    app components 
    import React, { Component } from 'react';
    import './App.css';
    import Char from './Char/Char'


    class App extends Component {
      state ={
        userInput: ''
      }

      handleChange =(e)=>{
this.setState({
  userInput: e.target.value
})
      render() {

        const charList = this.state.userInput.map(char =>{
          return (
            <Char character={char} />
          )
        })

        return (
          <div className="container">
          <div className="App card">
    <input type="text" placeholder="enter a text" 
      value={this.state.userInput} onChange={this.handleChange}></input>
      <p>Paragraph: {this.state.userInput}</p>

          {charList}

          </div>
        </div>
        );
      }
    }

    export default App;

Here is Char component 这是Char组件

import React from 'react'

const Char =(props) =>{

        const divStyle = {
            display: 'inline-block',
            margin: '16px',
            border: '1px solid pink',
            padding: '16px', 
            textAlign: 'center',
            backgroundColor: 'orange'

          };
        return ( 
            <div style={divStyle}>
           <p>{props.character}</p>
            </div>
         );
}

export default Char;

so when I run the app I get the following error 所以当我运行应用程序时,我收到以下错误

TypeError: this.state.userInput.map is not a function TypeError:this.state.userInput.map不是函数

What do I need to change to get rid of this distubing litle error? 我需要改变什么才能摆脱这种令人沮丧的痘痘错误?

There is no map method for a string. 字符串没有map方法。

You can make it an array easily enough: 你可以很容易地使它成为一个数组:

this.state.userInput.split('').map(c => <Char character={c} />);

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

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