React.Children.only expected to receive a single R

2020-02-10 06:50发布

问题:

I'm getting 'React.Children.only expected to receive a single React element child.' from the following code.

I have created a new react app using create-react-app and installed redux and react-redux, and created a simple reducer and creating store with that.

import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";

import logo from './logo.svg';
import './App.css';

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}


function productReducer(state = [], action) {
  return state;
}

const store = createStore(
  productReducer
);

ReactDOM.render((<Provider store={store}><App /> </Provider>), document.getElementById('root'));

回答1:

You have a space here:

                               ↓
<Provider store={store}><App /> </Provider>

JSX is kinda picky about spacing on single lines. The above essentially gets interpreted as:

<Provider store={store}><App />{' '}</Provider>

(In fact, Prettier will produce pretty much this exact output)

You can either remove the space:

<Provider store={store}><App /></Provider>

Or break it up on to multiple lines:

<Provider store={store}>
    <App />
</Provider>


回答2:

I had a similar problem and it turns out I had converted my App root from a function to a class, which means I had to change the syntax from this:

ReactDOM.render(
  <Provider store={store}>
    { App }
  </Provider>,
  document.getElementById('root')
);

To this:

ReactDOM.render(
  <Provider store={store}>
    { <App /> }
  </Provider>,
  document.getElementById('root')
);