【问题标题】:Reactjs Importing from the same directoryReactjs 从同一目录导入
【发布时间】:2018-10-12 16:40:40
【问题描述】:

我正在使用 Reactjs 构建一个 TODO 应用程序,在我的 components 文件夹中,我有一个名为 TaskList 的类,其中包含用于迭代任务的代码:

import React, { Component } from 'react';
import {connect} from 'react-redux';

class TaskList extends Component {
    render(){
        return(
            <table>
                <thead>
                    <tr>
                        <th>Tasks</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {this.props.tasks.map((task,index) => <Task key={index} task={task} />)}
                </tbody>
            </table>
        );
    }
}

function MapStateToProps(state){
    return{
        tasks:state.tasks
    }
}

export default connect (MapStateToProps)(TaskList);

此外,在组件文件夹中,我有一个名为 Task 的类,用于我的 TaskList 类:

任务:

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {DeleteTask} from '../../redux/actions';

class Task extends Component {
    render(){
        return(
            <tr>
                <td>
                    {this.props.task}
                </td>
                <td>
                    <button onClick = {() => this.props.DeleteTask(this.props.id)}>Delete</button>
                </td>
            </tr>

        );
    }
}

function MapDispatchToProps(dispatch){
    return bindActionCreators({DeleteTask},dispatch);
}

export default connect (() => {return {};},MapDispatchToProps)(Task);

我的问题是我有错误任务未定义,因为我没有将任务导入任务列表。在我已经尝试过的 TaskList 上:

import Task from './components/task';
import Task from 'task'; //as it's on the same directory
import Task from './task';

而且没有任何效果。对此有何想法?

【问题讨论】:

  • 我自己解决了错误,导入应该是 Import Task from '../task'
  • 将解决方案放在答案上并接受它。为了将来参考,导入写成import Thing from "module/path",其中Thing 必须匹配模块中的export default Thing 语句。
  • 我也使用 import { Task} from '.'; 让它工作。

标签: reactjs ecmascript-6 frontend


【解决方案1】:

我自己解决了错误,导入应该是

 Import Task from '../task' 

【讨论】:

    【解决方案2】:

    我知道 OP 解决了 OP,但它对我不起作用。这是我必须做的:

    import Task from '../components/task'

    经过一番调查,我发现项目树是从项目根目录开始的,所以必须从当前文件位置开始跟踪相对路径名,然后向上遍历(../)和向下遍历树(@987654323 @) 到导入的文件,如果你想指定相对路径。也可以指定绝对路径,如:

    import Task from 'C:/Users/devusr1/source/repos/React/hello-world/src/components/task.js'

    相对路径和绝对路径都对我有用(我使用的是 nodejs。)

    什么不起作用:

    .

    ./

    ../components

    ./src/components/task

    【讨论】:

    • 这对我也有帮助。我完全确定这里的机制,但我认为重要的是要注意这是由于 webpack 的性质,特别是。
    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多