错误:对象作为 React 子对象无效,React Hook 中的 prop 未返回

cki*_*ris -1 javascript reactjs react-hooks

我在尝试return ( <div id="info_side">{info}</div> )以下时收到错误。我有一个有效的_onClick功能,info如果我没有{info}在返回中包含任何地方,我可以控制台日志。我怎样才能解决这个问题?

这是错误: Error: Objects are not valid as a React child (found: object with keys {type, _vectorTileFeature, properties, layer, source, state}). If you meant to render a collection of children, use an array instead.

更新 必须将对象转换为数组,然后映射键值,现在它可以工作了。

const _onClick = event => {
  const display = event.features;
  if (display.length > 0) {
    setInfo(display[0].properties)
  }
}

var list = Object.entries(info).map(([key,value]) => {
  return (
    <div><span className="bold">{key}</span>: <span>{value.toString()}</span></div>
  )
});

return (
    <div id="info_side">{list}</div>
)
Run Code Online (Sandbox Code Playgroud)

原帖

const App = () => {
    const [viewport, setViewport] = useState({longitude: -98.58, latitude: 39.83, zoom: 3.5})
    const [locations, setLocations] = useState([])
    const [geojson, setGeojson] = useState(null)
    const [size, setSize] = useState({value: "All"})
    const [info, setInfo] = useState([]) 

    useEffect(() => {
        setLocations(geodata)
        _updateLocationData(size.value)
    }, [locations]);

    useEffect(() => {
        setInfo(info);
    }, [info]);

    const _updateViewport = viewport => {
        setViewport(viewport)
    }

    const _updateData = event => {
        setSize({value: event.target.value})
        _updateLocationData(event.target.value)
    }

    const _updateLocationData = (sizeValue) => {   
        var tempLocations = [];
        locations.forEach(function(res) {
            if (sizeValue === "All") {
                tempLocations.push(res);
            } else if (res.Size === sizeValue) {
                tempLocations.push(res);
            }
        });
        var data = {
            type: "FeatureCollection",
            features: tempLocations.map(item => {
                return {
                    id: ...,
                    type: "Feature",
                    properties: {
                        Company: item.Company,
                        Address: item.Address,
                        Phone: item.Phone,
                        Long: item.Long,
                        Lat: item.Lat,
                        Size: item.Size,
                    },
                    geometry: {
                        type: "Point",
                        coordinates: [item.Long, item.Lat]
                    }
                };
            })
        };
        setGeojson(data);
    }

    const _onClick = event => {
        const { features } = event;
        const info = features && features.find(f => f.layer.id === 'icon');
        setInfo(info); // Error: Objects are not valid as a React child (found: object with keys {type, _vectorTileFeature, properties, layer, source, state}). If you meant to render a collection of children, use an array instead.
        console.log(info) // I can see the object with no error here if I do not add {info} in return ( <div id="info_side">{info}</div> )
    }

    return (
      <div className="App">
        <div className="inner-left map-container">
          <ReactMapGL
                {...viewport}
                onViewportChange={_updateViewport}
                width="100%"
                height="100%"
                mapStyle={mapStyle}
                mapboxApiAccessToken={TOKEN}
                onClick={_onClick}>

                <Source id="my-data" type="geojson" data={geojson}>
                    <Layer {...icon} />
                </Source>

                <div style={navStyle}>
                  <NavigationControl onViewportChange={_updateViewport} />
                  <select onChange={_updateData} defaultValue={size.value}>
                      <option value="All">All</option>
                      <option value="Large">Large</option>
                      <option value="Medium">Medium</option>
                      <option value="Small">Small</option>
                      <option value="Very Small">Very Small</option>
                  </select>
              </div>
          </ReactMapGL>
        </div>
        <div className="inner-right info-container">
          <Nav />
          <Search />
          <div id="info_side"> // where is error is thrown if I have {info} below
            <div className="company">{info.properties.Company}</div> 
            <div className="address">{info.properties.Address}</div>
            <div className="phone">{info.properties.Phone}</div>
          </div>
        </div>
      </div> 
    );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

小智 7

信息是一个对象,所以你不能这样做:

<div id="info_side">{info}</div>
Run Code Online (Sandbox Code Playgroud)

每次在 React 的 DOM elemnet 中使用 {} 时,{} 中的变量必须是字符串、数字或布尔值。因此,您必须确保在括号内使用原语。

尝试{JSON.stringify(info)}或您想要的任何变量,您将看到该值的字符串表示是什么。