【问题标题】:React - 'state' is assigned a value but never used no-unused-varsReact - 'state' 被分配了一个值,但从未使用过 no-unused-vars
【发布时间】:2021-04-13 17:24:35
【问题描述】:

我有此代码,但收到错误消息:

src/App.js 第 5:11 行:“state”被分配了一个值,但从未使用过 no-unused-vars。

我做错了什么? 感谢您的帮助!

import Some from './Some/Some';

const App = () => {
    const state = ({
        persons: [
            {name: 'Connor', text: 'This is first.'},
            {name: 'Megan', text: 'This is second.'},
            {name: 'Jcob', text: 'This is third.'}
        ]
    }
);
    return (
        <div className="App">
            <h1>Hi, React!</h1>
            <Some name={this.state.persons[0].name} text={this.state.persons[0].text} />
            <Some name={this.state.persons[1].name} text={this.state.persons[1].text} />
            <Some name={this.state.persons[2].name} text={this.state.persons[2].text} />
        </div>
    );
}

export default App;

【问题讨论】:

  • this.state?看起来你在一个功能组件中(没有“this”)

标签: reactjs


【解决方案1】:

您应该只在类组件中引用this.state。在函数式组件内部,没有this,只有局部变量。

虽然您可以更改为:

<Some name={state.persons[0].name} text={state.persons[0].text} />

使用.map 会更有意义,就像只声明一个没有周围对象的persons 数组一样:

const App = () => {
    const persons = [
        {name: 'Connor', text: 'This is first.'},
        {name: 'Megan', text: 'This is second.'},
        {name: 'Jcob', text: 'This is third.'}
    ];
    return (
        <div className="App">
            <h1>Hi, React!</h1>
            {
                persons.map(p => <Some name={p.name} text={p.text} />)
            }
        </div>
    );
}

如果你需要一个功能组件中的实际状态,你应该使用useState,例如:

const [persons, setPersons] = useState([
    {name: 'Connor', text: 'This is first.'},
    {name: 'Megan', text: 'This is second.'},
    {name: 'Jcob', text: 'This is third.'}
]);

(但当前组件看起来并没有做任何有状态的事情,至少现在还没有)

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 2020-04-21
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多