如何在React中拆分道具字符串?

时间:2017-05-01 15:23:24

标签: reactjs split

我有My React功能组件接受道具字符串x,这给了我'props.x.split不是函数'错误。但是,当我用完全相同的字符串覆盖道具时,我没有任何错误,请参阅下文:

function My(props) {  
    console.log(typeof props.x, props.x); //string 41.9980,-71.4941      
    const loc = '41.9980,-71.4941'; //overriding arguments
    console.log(typeof loc, loc); //string 41.9980,-71.4941
    const lat = loc.split(",")[0].toString(); 
    const lon = loc.split(",")[1].toString();    
    return <h6>{lat,lon}</h6>;  //41.9980,-71.4941
}

但是这个不起作用:

function My(props) {  
    console.log(typeof props.x, props.x); //string 41.9980,-71.4941  
    const loc = props.x     
    const lat = loc.split(",")[0].toString(); // Uncaught TypeError: loc.split is not a function 
    const lon = loc.split(",")[1].toString();    
    return <h6>{lat,lot}</h6>;
}

更新:使用我的功能组件的主要组件

class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      location: []     
    }; 
  }
  getLoc() {
    axios.get('http://ipinfo.io')
      .then((res) => {      
        this.setState({location:res.data.loc});        
      })                
  }

  componentDidMount() {    
    this.getLoc();     

  }
  render() {
    return (
      <div >          
            <My x={this.state.location}/>                                       
      </div> 
    );
  }
}

0 个答案:

没有答案