用于反应的控制台日志记录?

我是超级新的反应,我正在努力得到它设置为流星和拼凑东西从其他来源也。其中一个来源为应用程序设置了控制台日志记录,但是我使用的是 ES6/JSX 方式,所以仅仅使用他们的代码对我来说不起作用(或者看起来不起作用)。

我找到的一些用于日志记录的代码是

import Logger from 'simple-console-logger';
Logger.configure({level: 'debug'});

但我看到了这个错误 cannot find module './dumy'

我还尝试使用 react-loggerreact-console-logger,但没有用。这是我的后者代码,我相信它应该可以工作。

import {Logger, ConsoleLogger} from 'react-console-logger';
const myLogger = new Logger();
export default class App extends Component {
render() {
myLogger.info('something witty');
}
}

然而,myLogger.info('...')正在向 node_modules/react-console-logger/lib/Logger.js打电话,它将其定义为

picture of code since copy-paste doesn't work

而且 this.logger是未定义的,虽然我看到它被定义在上面?

有人知道我哪里做错了吗?在我看来,这个库是错误的,但是也许它与我使用 JSX 文件而不是 js 有关?

384196 次浏览

If you're just after console logging here's what I'd do:

export default class App extends Component {
componentDidMount() {
console.log('I was triggered during componentDidMount')
}


render() {
console.log('I was triggered during render')
return (
<div> I am the App component </div>
)
}
}

Shouldn't be any need for those packages just to do console logging.

Here are some more console logging "pro tips":

console.table

var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];


console.table(animals);

console.table

console.trace

Shows you the call stack for leading up to the console.

console.trace

You can even customise your consoles to make them stand out

console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}


console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}


console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

console.todo

If you really want to level up don't limit your self to the console statement.

Here is a great post on how you can integrate a chrome debugger right into your code editor!

https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

const Console = prop => (
console[Object.keys(prop)[0]](...Object.values(prop))
,null // ➜ React components must return something
)


// Some component with JSX and a logger inside
const App = () =>
<div>
<p>imagine this is some component</p>
<Console log='foo' />
<p>imagine another component</p>
<Console warn='bar' />
</div>


// Render
ReactDOM.render(
<App />,
document.getElementById("react")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>