React:函数以未定义的形式返回

时间:2019-08-27 15:36:06

标签: javascript reactjs react-native object react-hooks

摘要

我在功能组件内部拥有以下功能,这些功能不断变得不确定。该函数内部的所有数据,tableData和subtractedStats均已定义且准确。

这可能只是我正在制作的一小段JavaScript,因此将非常感谢您的帮助!

代码

这是下面的功能组件:

const TableComponent = ({ tableData }) => {
  formatTableData = () => {
    console.log("inside sumDataFormat", tableData);
    return tableData.forEach(competitor => {
      let subtractedStats = [];
      console.log("competitor in", competitor);
      for (const i in competitor.startingLifeTimeStats) {
        if (competitor.startingLifeTimeStats[i]) {
          competitor.stats
            ? (subtractedStats[i] =
                competitor.stats[i] - competitor.startingLifeTimeStats[i])
            : (subtractedStats[i] = 0);
        }
      }
      console.log("subtractedStats", subtractedStats);
      return subtractedStats;
    });
  };

  useEffect(() => {
    console.log("formatTableData", formatTableData());
  });
}

编辑:

有人可以帮助我解决此代码中的错误(如何解决此问题吗?),并可以简要说明功能组件

3 个答案:

答案 0 :(得分:3)

forEach函数不会返回任何内容,它只是遍历数组,为您提供一个undefinedmap函数可能就是您想要的:

  formatTableData = () => {
    console.log("inside sumDataFormat", tableData);
    return tableData.map(competitor => { // This returns another array where every element is converted by what's returned in the predicate

答案 1 :(得分:1)

功能组件是最基本的一种React组件,由组件的(不变)道具定义。

功能组件需要返回一些 JSX代码(UI) (也可以为 null )。 这是最基本的功能组件的示例

const App = () => {
  const greeting = 'Hello Function Component!';
  return <Headline value={greeting} />;
};
const Headline = ({ value }) => {
  return <h1>{value}</h1>;
};
export default App;

解决方案代码

以下是上述示例作为功能组件的解决方案 这是下面的解决方案,使用hooks将数据保存到组件的状态,还使用生命周期方法来解析componentDidMount上的数据:

const TableComponent = (props: ) => {
    const [state, setState] = useState(initialState)

    // componentDidUpdate
    useEffect(() => {
        setState(getData(props.data));
    }, []);

    // getData() - Parser for data coming inside the functional Component
    const getData = (tableData) => {
        return tableData.map(competitor => {
            return competitor.startingLifeTimeStats.map((item, index) => {
                return item && competitor.stats ? competitor.stats[index]-item : 0;
            })
        })
    };

    // UI (JSX)
    return (
        <Text>{JSON.stringify(state)}</Text>
    );
}
export default TableComponent;

答案 2 :(得分:0)

尝试使用下面的地图示例代码。

render() {
return (<div>
{this.state.people.map((person, index) => (
<p>Hello, {person.name} from {person.country}!</p>
))}
</div>);
}