Javascript - Interesting questions
React Native App
NEW QUESTIONS
-
APP: In
components/LaunchScreenBackdrop/styles.js: Why is undefined used here?``` image: {flex: 1, width: undefined, height: undefined, },
- APP: In
src/common/localstorage/LocalStore.js: Why do you create instances as static members within their own class and not outside of that class? Below defining the class you’re exporting them anyway..
-
Proxipedia Mobile App: Explain performance optimization of_prepareDataSourceinPoiGridand_dataSource(props)inPoiDetail.js.- Das sagt der Liste: “Nimm bitte
itemsIdsals keys.” - Hier wird jetzt mit
itemIdseine custom Id liste cloneWithRows mitgegeben:return ds.cloneWithRows(itemsMap, itemsIds);. Defaultmäßig benutzt cloneWithRows die indices als id’s. rowHasChangedwird zunächst aufgerufen. Mit normalen indices würde der hier feststellen, dass sich nach Beacon-Sorting alle indices-Objekt Verbindungen anders sind und nun die einzelnen Items der Liste neu gerendert werden müssen. Mit- In die
dataSourceGeschichte der React List Komponente schauen, um das alles besser zu verstehen, was React da under the hood macht. - Die Zeile
if (maxItems) m = Math.min(items.length, maxItems);mitmaxItemsist eine Peformance Optimierung im Zusammenhang mit dem Placeholder-mode.
Andere Idee in der Liste:
Placeholder-mode- Rendere bis alle Animationen vorbei sind nur die ersten paar Items (hier wurden drei Stück gewählt, weil sie einen ganzen App Screen füllen) und erst danach noch den Rest. Der User merkt nichts und die Performance ist besser.
- Das sagt der Liste: “Nimm bitte
-
Time: Explain syntax of
return +(new Date());inartirigo-library/lib/util/time/now.js. WhynowMethod()?Answer:
+()ist ein integer cast erzeugt hier aus Date timestamp -
Was hat es mit
scripts/test/mocksauf sich?- Ein paar modules müssen in Tests gemockt werden, damit die Tests noch funktionieren.
- Use babel for
nodeModulesBabelinscripts/test/compile.js. Hier werden die tests, die ES6 drin haben mit Babel compiliert.
-
Explain the whole version management please. Running
code-pushAndroid without--targetBinaryVersionflag gives error[Error] No property named "getVersionName()" exists in the "android/gradle.properties" file.Answer: Wir geben Version nummer erst beim builden mit Fastlane mit und nicht direkt im Android code. Mit
--targetBinaryVersiongeben wir die Version also explizit schon beim code-push Befehl an und er versucht nicht die Android Versions-Nummer aus den gradle files rauszulesen.
- In
scripts/flavor-copy.js, warum.then((data) => { i18nFlavor = data; })? -
What’s going on here in
POIGrid.js?reactMixin(PoiGrid.prototype, TimerMixin); - Warum wird
_prepareDataSource(items, maxItems) {inPoiGrid.jszweimal aufgerufen undconsole.log('itemsMap', itemsMap); console.log('itemsIds', itemsIds);liefert unterschiedliche Ergebnisse? -
What does happen here in
Api.js?// if no contentVersion is in the result but we got data // we can savely say, that's it's the current version // otherwise it would return an error responseJson.contentVersion = this._contentVersion; - Was macht
export const navigation = false;inPoiDetailContainer? -
In
comonents/Audio.js:-
Why did you define the methods as
static?Answer?: So that you can call it without having to get hold of the Audio instance?
-
Follow up question: How would you get hold of the particular Audio instance?
Answer?: Via a
refwhich is stored in the state? - in static function
load: Why do you have to// replace file-protocol?
-
-
In
artirigo library:- What does
ConditionalRendercomponent do? - How does
_computeSyntheticStateinButton.jsimprove performance?
- What does
TODO in Proxipedia Mobile App:
-
Investigate
measureinLightBoxTrigger.js:this._root.measure((x, y, width, height, pageX, pageY) => {
- when rendered, I get size of view. part of every view. - But how does the whole thing work here?
- Test 2 modals at the same time!!! Just dispatch an alert directly after the gallery or so..
- Refactor
texttostoryin action. - Check out how
progressCallbackinApi.js/uploadworks. - Play around with and understand the video-player rotation transform animation! and how the
Animated.Viewlives inside theVideocomponent. -
Check out swipe up animation —> Header disappearing.
—> Investigate
PoiDetailNavHeaderinPoiDetail.js. - How did you solve Android fetch finally work with form data?
- Pointer events… difference?
- Understand the routing and how it works together with actions/redux state
- Understand Animations! —> Play around with animation values in simulator \w hot reloading.
- How to rename a RN project. —> Try it again.
- Testflight —> upload build
- Codepushify an app
-
Fully understand this code (i.e. from
Animatedclass), i.e. what does the?do? It should mean optional. But just check:type TimingAnimationConfig = AnimationConfig & { toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY; easing?: (value: number) => number; duration?: number; delay?: number; }; ``` **Partial Answer**: Introducing strict typing into JS I think that's the FlowType syntax! **TODO**: What does the question mark exactly stand for? and ```js var timing = function( value: AnimatedValue | AnimatedValueXY, config: TimingAnimationConfig, ): CompositeAnimation { return maybeVectorAnim(value, config, timing) || { start: ..., stop: ..., }; }; ``` -
Understand this code from
scripts/flavor-copy.js:fs.readdir(flavorI18nDir, (err, items) => { // folder exists if (!err) { // items.reduce( (sequence, fileName) => ( sequence.then(() => mergeI18nFiles(fileName)) ), Promise.resolve() ).then(() => next()); } else { next(); } }); ``` **Partial Answer**: Ingenious use of `array.prototype.reduce`! Creates a `Promise chain` by starting with `Promise.resolve()` and adding `.then()` calls along the way! **Still TODO**: Fully understand the `next()`! - Go through all
ListViewproperties inPoiGrid. - Finish test function with
bind()+ additional new input -
In
actions/push_notifications.jsI had to write:PushNotificationIOS.addEventListener('notification', (notification) => onPushNotification(notification, dispatch)); ``` because the following led to the error that `dispatch` is not a function ```js PushNotificationIOS.addEventListener('notification', onPushNotification); ``` Why does `onPushNotification` not have access to `dispatch` here? **Maybe Answer??** ----> Because `dispatch` function is not declared in that scope. Instead of `onPushNotification` try `() => onPushNotification`. ??? -
Selectors:
in
react-boilerplate: Incontainers/HomePage/selectors.jsselectHomeexpects the entirestate. But the line(homeState) => homeState.get('username')expects thehomeStatewhich is on a deeper level. Then later inHomePage/index.jsit is called inconst mapStateToProps = createStructuredSelector({ repos: selectRepos(), username: selectUsername(), loading: selectLoading(), error: selectError(), });and here all is on the same level as the other selectors? But don’t they expect different levels of the store??
- PP1.5 App: How does
fullscreenTogglwork? -
PP1.5 App: Understand
_getContentinLightBoxTrigger.js:_getContent = () => { const { children, activeProps, } = this.props; if (activeProps) { return cloneElement( Children.only(children), activeProps ); } // use children as they are return children; }; ``` **Answer**: `cloneElement` merges `activeProps` with the own props of the single child (see [React docs](https://facebook.github.io/react/docs/top-level-api.html#react.children)) i.e. just some additional props are passed to the child if it is active.
Questions of CMS React Frontend
-
Can you explain this in
ContentContainer.jsstyles:.mainScroll { flex: 1; overflow-y: scroll; /* has to be scroll, not auto */ -webkit-overflow-scrolling: touch; }ANSWER Verhalten wie am Telefon — runterziehen
In same file,
right: autodoesn’t seem to have any function, or does it?:.drawerSeperator { composes: seperatorLeft absoluteFill; right: auto; }ANSWER Take width instead of
right:0which comes fromabsoluteFill. -
Why does this in
.mediaLibrary__itemshinder the text to overflow?.absoluteFill { position: absolute; top: 0; right: 0; bottom: 0; left: 0; }Ganzer screen.
-
In
MediaLibraryComponent styles:.btnClose { position: absolute !important; transform: translate(0, -50%) !important; display: block; right: 0; top: 50%; }margin-top: -30pxin allen browsern.- top beziehen sich auf container in dem .btnClose drin ist.
- transform -50% beziehen sich auf element selbst.
-
Selectors: Why are they wrapped in a function? e.g. (In the example in the boilerplate docs they are not wrapped)
const selectRepos = () => createSelector(selectGlobal(), (globalState) => globalState.getIn(['userData', 'repositories']) );- If you use a function it creates a new selector each time.
- With
propsit makes sense to wrap it in a function. - Also in
HomePage/selectors.js: Why is selectHome again wrapped into an empty function, if it is directly called thereafter inselectUsername??
-
In
redirectToLoginhook and in homePath logic inroutes.js:Why is it
!isAuthenticatedand notisAuthenticatedinif (!isAuthenticated) replace(RouteId.home);?Shouldn’t it only go to home if a user is authenticated??
Or does it mean, if a user is not authenticated, go to home which will be redirected to login, but there the logic is also inversed in my sense…
-
In
app/app.js, how does thisPromisework?let storeReady; const storeReadyPromise = new Promise((resolve) => { storeReady = resolve; });ANSWER Speicher storyReadypromise resolve funktion.
-
Was macht diese Zeile anderes als
{children}z.B. inContentcontainer/index.js?Children.map(children, (child) => child);Spuckst du hier z.B. die
lielemente einerulaus? -
In
MultiLocaleContent/index.jsWarum werden hier nicht auch der Inhalt von
ObjectPage/index.jsgerendert?{ cloneElement(Children.only(children), { locale: item.locale, isDefaultLocale: item.locale === defaultLocale, data: item, }); }Einfach Property
children—> die wird bearbeitet. -
How to understand this?
defaultMessage: '{data, plural, \n=0 {Draft}\n=1 {Published}}',\nwegen JSLint um neue Zeile darzustellen.- format.js
-
Zum
redux-persist. Wie genau funktioniert das? Sucht das dann automatisch erstmal im Browser, ob da noch etwas abgespeichert ist beim mounten vom redux store?—> Redux persist - auch nur laden und speichern.
store.js- in debugger in
Application->Local Storage
- CSS modules variables don’t
General
-
In React the life-cycle methods may be called as:
componentWillMount() { ... }This is not a function call
componentWillMount({ ... })or a function declarationfunction componentWillMount() { ... }or a function expressionconst componentWillMount = function() { ... }What is it? - Is this a prototype method call? Or a ES6 JS method call?
Answer: It is syntactic sugar for a
method definition(see these docs) —> See my JS theory document about ES6 classes. -
If both, a function expression and a method definition, occur within the same class, what’s the difference? I.e. what’s the role of the function expression here?
Answer: Martin uses function expressions often because of the ES6 binding feature.
Answered:
-
Why is
fetchDatadefined as a class method in most classes and not as a function expression as most of the other functions? Because it is called incomponentDidMount?Answer: To make use of ES6 binding feature of function expressions.
-
Why are these two lines the same? Explain semi-colon:
onChange={event => this._handleChange(event.target.name, event.target.value)} onChange={({ target: { value } }) => this._handleChange('desc', value)}Answer: Using ES6
destructuring! -
Investigate: How does
classNamesfromimport classNames from 'classnames';work?Answer: Dynamically add
classnamesbased on boolean expressions. -
In
ObjectPage/reducer.js:Why is this better than creating new
ObjectLocalizedState?object = ObjectLocalizedState.fromJS({ id: action.id, objectId: action.objectId, locale: action.locale, });ANSWER: Found the answer:
fromJSis a custom field defined in the filerecords.jsin whichObjectLocalizedStateis defined.fromJSincludes the call ofnew ObjectLocalizedState. -
PROMISES: In
api/index.js:const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));cosnt delay = (ms) => ( new Promise(function(resolve) { return setTimeout(resolve, ms) }) );Why set the
resolvePromise as argument forsetTimeout?Answer: It’s the callback of setTimeout!! After the timeout finishes, just resolve the Promise - no more needs to be done here!
-
Where does prop
locationcome from? i.e. how is passed to the containers from the router?Answer: From react-router or from the window.location object.
OLD QUESTIONS
Javascript Questions
New
-
First-class functions
in book
most-adequate-guideto functional programming, he never uses the arguments in the first-class functions examples. E.g. he says the following two examples are equivalent (page 38):“// go back to every httpGet call in the application and explicitly pass err // along. httpGet('/post/2', function(json, err) { return renderPost(json, err); });// renderPost is called from within httpGet with however many arguments it wants httpGet('/post/2', renderPost);”Where did the arguments
jsonanderrgo? -
Redux
-
e.g in
POIDetailContainer.js, what are theownProps?props passed to container, e.g.
navigationStatefromApp.js -
What are
navigationState?e.g. see
container/App.js:const RouteComponent = Routes[props.scene.navigationState.key].component; <RouteComponent key={props.scene.navigationState.key} navigationState={props.scene.navigationState} />naviationStateprop, um poi id mitzugeben.—> NavigationExperimental anschauen —> actions/naviagation
- In
Exhibition.js:ownProps.navigationState.idis the root poi.. why?
---> NavigationExperimental anschauen —> actions/navigation
-
what does the
.reduce((result, group)function do? Is it from redux? e.g.header: header.reduce(mediaReduce, []),orreduce function
in
lodashthere is a reduce function. But now it is called on e.g.poi.layout.bodydirectly, i.e.poi.layout.body.reduce()—> reduce function is part of core Javascript
-
-
Proxipedia
- Where does the prop
stylecome from inListItemImage.js? It’s not set as prop inDetailViewwhen it is called.
—> it is not required. style can be set if needed.
- Where does the prop
-
Proxipedia: In
NavigationList.js, where does the parameterscrollPropscome from in:```js renderScrollComponent={(scrollProps) => ( <ScrollView {...scrollProps} alwaysBounceVertical={false} />)}
from `<ListView/>` -
Proxipedia: How is a detail, i.e.
NavigationDetailrendered inNavigation.js?Configuration in
navigation/index.js—> mapping to Components inNavigation.js -
Proxipedia: What’s the
modalStatein e.g.App.js?check out
modalPushandmodalPop—> look at redux state -
Proxipedia:
<LightBox />is rendered inApp.js. How is the Lightbox called fromLightBoxTrigger?`if (!isOpen) return null;
{modalState.isOpen ? <LightBox {…modalState}> : null`
-
in
src/common/localstorage/index.js-
export default new Local(schema);is exported. Well, whichschemawill that be?—> Not in the app anymore. Check out
realm - so
Realmexposes an objectrealmSchemato the file in which it is imported?
-
-
How does the following export of common button styles function work?
—> caching mechanism. Args are saved.
export const styles = (...args) => { const argsString = args.join(',') || 'DEFAULT'; // no stylesheet created for this setting -> create if (!map[argsString]) { map[argsString] = StyleSheet.create(stylesSrc.apply(this, args)); } return map[argsString]; }; -
Why do I need
export { default } from './ComponentName';inside eachindex.jsadditionally toexport * from './ComponentName';?with * only named exports are exported, not default.
-
In
Waypoint.styles.js, where isstyles.footerTextdefined?export default { ...styles, footerText: [globalStyles.smallCopy, styles.footerText], };—> not on purpose.. probably a copy-paste error
-
How does
util/time/now.jswork?+(new Date()): cast into number —> creates unix timestamp -
Default values for props are now set in
defaultPropsand not inconstructoranymore..Why is
MyComponent.defaultPropsthe same asstatic defaultProps?? -
How does storage work?
—> look at
util/fsfiles -
in
ListItemVideo.js:{ description && '\n'; } <Text style={[textStyles.smallCopy]}>{description}</Text>;Um die Lehrzeile hinzuadden wenn es eine description gibt. Gibt den letzten Wert aus wenn er True ist.
-
According to React documentation
this.props.childrencan be either an array or an object if there’s only one single child. Is{this.props.children}robust against that????
-
In
LightBoxTrigger.js:What does
Children.only(children)do and why do we need it here?if (activeProps) { return cloneElement(Children.only(children), activeProps); }Probably check whether only one child in children.
-
measurefunction inLightBoxTrigger.js:What does this function do?
this.refs.root.measure(when rendered, I get size of view. part of every view.
-
Navigation e.g.
container/Home.js. What do functionsrightandleftdo?See
App.js—> render whatever is in right or left part. -
What does the action
navigateReset()do?resets the navigation.
-
How is
modalStateinApp.jsconnected tomodalStateReducer?ES6 syntax shortcut let’s it appear so, but via default export it works.
- How could I get information about the current POI inside an action creator which I build like
actions/menu.js? i.e.story.jsin commitbcfb7f86e2ed4c21435353dd1821c2838668ef82 -
Why start with return statement within action creator with
Promise.resolve()?return ( Promise.resolve() // TODO determine which languages to load .then(() => api.languages()) );—> because Martin thinks it looks nicer!
-
Javascript Closures - debounce
—> read article
-
How to create a flavor?
Discussed + instructions created
Some new questions (June 21 ff)
-
Webstorm: Is it okay to deactivate the
Babelfile watcher in our projects. We’re using the ‘react-native’ thing.—> Mal gucken wenns nochmal kommt..
-
Can redux async actions be passed to stateless Component from Container via mapDispatchToProps?
YES! It can!
My comment: We just pass
dispatchmethod and then import the action inside the component to then calldispatch(someAction). Is this the only way to do it? -
Why do you use the
XMLHttpRequest();in theuploadfunction inApi.jsand notfetch?fetchhat keinenonprogresscallback to show progress. -
Why did you create an Api class?
- Initialization + ..perhaps easier to make it more generic
- As an instance I am more flexible.. can create second api class instance with e.g. other parameters. (~Singleton implementieren)
-
Error when running
npm run debug:androidwith Genymotion:Starting the app on 192.168.58.101:5555 (/usr/local/opt/android-sdk/platform-tools/adb -s 192.168.58.101:5555 shell am start -n de.artirigo.whazat/.MainActivity)... Starting: Intent { cmp=de.artirigo.whazat/.MainActivity } Error type 3 Error: Activity class {de.artirigo.whazat/de.artirigo.whazat.MainActivity} does not exist.—> Manually start app
-
In
CameraActionContainer, why don’t you define the followingonActionas a redux thunk?:onAction: (...args) => ( Promise.resolve() .then(() => dispatch(upload(...args))) .then(() => dispatch(feedResetTimestamp())) .then(() => dispatch(navigatePop())) ),These actions calls together only appear here together and they all are from different actioncreator files.
-
In
FeedItem.js, warum sollte es in der folgenden Zeile jemals keinonImagegeben? Wird doch immer weitergegeben..const ContainerComponent = onImage ? TouchableOpacity : View;Wahrscheinlich wirft
onImage: () => {},hierfalse. This is set in parent componentFeedas default-props.If I don’t pass the
onImageproperty it will be false. -
In
NavigationStateUtils.jsofNavigationExperimental: Do you know why in thepopfunction inindex: lastChildren.length - 2,the index is reduced by 2?one child: index = 0, two children: index = 1.
-
Navigation: How is the correct image accessed?
navigatePushand the corresponding reducer don’t handle theidwhich is the image ID..const onImage = (imageId) => navigatePush({ key: RouteId.Detail, id: imageId, });In
DetailScreenContainer.js:const imageId = ownProps.route.id;. The content of DetailScreen is set like this. -
In general: What is the difference between
pushandjumpToIndexin routing? Why do I need the later anyway?we use
navigateResetto reset the stack. e.g.Favoritesbecomes index 0 when clicking Favorites from Home in Proxipedia 1.5 -
In constructor of React class:
this.state = { ... }vs.state = { ... }? The same? Why can I actually callthis.statein a stateless component??stateis an instance variable. —> Try: setState() sollte in stateless component nicht funktionieren… -
Explain syntax of stateless component. It is not a class, so it does not need a constructor for props.. But how does it work?
- Like only having the render function.
- Be aware: entire stateless component is executed when rerendering.
- No refs are possible in stateless components
-
Javascript: Two different ways of defining properties of objects which are then called with the dot
.operator:someArray.lengthvs. e.g.Animated.timing(...).start():lengthis defined as:Array.prototype.length = 0;inEcmaScript.js. (and all other functions of array like e.g.toString)start()insideAnimated.jsis basically defined astiming = () => ({ start: () => {...} })
What’s the difference?
-
In component
CameraAction.js: What is a React mixin? How does the_mixinFrameStyle()thing work?this.setState(this._mixinFrameStyle({ currentAction: ACTIONS.CAMERA, }));Answer:
- A mixin mixes something to the response, i.e. here the
_mixinFrameStyle()mixes the orientation which is stored in an instance variable_lastOrientation(received from an event listener callback) into the store during thesetStatecommand. - A mixin was created here because this setting of orientation in the state is used at several places.
- Mixins can be chained, one for each functionality.
- If the orientation were just written in the state here, the orientation frame would also change if we are in the child component
PhotoDecidein which we don’t want the frame to change. When going back to the camera from here, we again want the frame to change, so the mixin is called here, when the state is set.
Is this just squeezing a thing to do directly before setting the state in
setStategiven some variable, right? - A mixin mixes something to the response, i.e. here the
-
How do you update a new version patch version of
artirigo-library?Just increase version number in
package.jsonin new commit.
Newest questions (14.07. ff)
-
scripts/flavor.js- Explainasync.seriesandworkplan.Call the script with
node --harmony scripts/flavor.jsOr call as
npm run flavor -- --flavor-name='test' - Ask about commit:
40c6077use ItemMap instead of Array for PoiGrid-ListView to avoid unnecessary rerenders - Ask about commit:
ba23665beacons noise filtering - Ask about commit:
87cca3eupdate proxipedia launch-screens and icons - Ask about commit:
48bbb8eenable LayoutAnimation on android - Ask about commit:
de2ab7bPA-113: display real download progress via file size from server - - Ask about commit:
7f6fab7PA-154: display bundle size in ‘download’ button - Ask about commit:
949ae9afastlane: add android release lane - Ask about commit:
a51b5a2add ResponsiveImage Component - Ask about commit:
1a7129aadd react-addons-shallow-compare, style-equal plugins - Ask about commit:
202696dPA-301: PoiDetail placeholder state and826f773PA-301: PoiGrid placeholder state - Martin Rädlinger - What is the
sinonpackage and where do we use it? - Learn from mistakes: What is bad about the CMS front-end code?
- Resize gallery image on drag —> Where is it implemented?
- flow?
- react native cli —> generator . What are generators?
-
Ist die story box keine
Lightboxmehr?—> Doch! Siehe die nächste Antwort.
-
Wo called
LightboxTriggerdieLightbox?\—> über
props.onOpenwelches nach oben propagiert diemodalOpenaction auslöst. Diese wiederum hat Einfluss auf denModalStackund der zeigt dieLightbox. -
Fastlane:
-
In
platform:ios,private_lane :build_appwas ist diecase options[:publish] == 'device'?* —> Build on device to show others.
-
Wie ruft
apply_flavorscripts/flavorundscripts/flavor_copyauf? * —> FOUND IT: Infastlane/actions/apply_flavor.rb* In der lane
alphagibt esconfig = load_flavor(options)—> Wo ist der output vonload_flavor()festgesetzt? - Wo wird
PROXIPEDIA_APP_CONFIGgesetzt? Was ist das?
-
-
What do the npm scripts
bundle:iosandbundle:androiddo?—> Old scripts to bundle the code —> Now done by
fastlaneand inJenkins -
Why do
deploy:iosanddeploy:androidwork asfastlane iosandfastlane android?—> Probably defaults
-
PP 1.5 App- State is initialized as aMapinpoisReducer.js. So why can you then merge it with aSeq? Why don’t you initialize it as aSeqin the first place?case BUNDLE_UPDATE_DATA: return state.mergeDeep( new Seq(action.data.pois) .map((value) => new PoiState(value)) .toMap() );—> Because
Seqis only temporarily… it’s a map here, because order doesn’t matter! -
Was machen die zwei Anführungszeichen in
return !!dispatch(navigatePopIfNotHome());inApp.js?- This is the
Bang operator—> Makes it a boolean! - Am I right that.. here the action is dispatched and then the boolean is returned of what dispatch returns. What does
- This is the
Answered on 2016/09/09
-
In your 1.5 App scripts (and also in the react boilerplate) why do you use
require('package_name')but also ES6 syntax arrow-style syntax and don’t useimportwhich babel can translate torequire?node --harmonyunterstuetzt einige ES6 features aber noch nichtimportundexport.babel-nodewürde das.babelrcwelches wir fuer React eingestellt haben, benutzen.
-
How do I delete the
webpackcached offline files in Chrome Dev Tools?- DevTools/Application/Clear Storage
-
Why do we have this in the reducers?
Falls vom Server z.B. ein State in nicht immutable form reinkommt..
if (!(state instanceof InitialState)) return initialState.mergeDeep(state);
-
Do callback functions always have to be wrapped inside an empty function? e.g.
// --file.js-- function getJSON(url, callback) { let xhr = new XMLHttpRequest(); xhr.onload = function () { callback(this.responseText); }; xhr.open('GET', url, true); xhr.send(); } export function getUsefulContents(url, callback) { getJSON(url, (data) => callback(JSON.parse(data))); }// --main.js-- import { getUsefulContents } from 'file'; getUsefulContents('http://www.example.com', (data) => { doSomethingUseful(data); });—> I don’t think so… Look at it more closely!
Asked (most of)
-
export defaultandexportin one filee.g.
export default Icon; export { glyphMap };Set the default export if nothing is specified and then the other exports.
-
Does
export * from './crud';export everything from all subfolders in./crud?No, it does not.
index.jsin folder is exception. If anindex.jsfile exists, -
Why does this tell me whether the item is immutable? in
crud/index.js?export const isImmutable = (item) => typeof item.toJS === 'function';—> Because that’s the way an immutable.js object is defined. An immutableJS object has a
toJSproperty which is of typefunction. Of course this test is not completely robust, but good enough in this scenario.
React Redux
-
In
connect, i.emapDispatchToPropsin a container, what is the difference betweenstate => stateandstate => ({})?- this components state (subset of the redux store) is available as props.
- no fields from the current state will be available as props.
-
Wenn
connectso gerufen wird, ist es dann das gleiche, wie einfach ohne connect, sprichexport default App?:export default connect((state) => state)(App);No! Because connect makes redux features, i.e. dispatch method and custom actionCreators and the redux state have to be made available in the container.
So the dispatch method or a method
Pure function —> has a reference to the store in it.
Idea of redux —> move dispatch with a reference to the store around.
default of mapDispatchToProps:
dispatch => dispatch(i.e. make thedispatchfunction available as props.As pseudo-code:
(dispatch) => { dispatch, bindActionCreators(myActionCreator), bindActionCreators(myActionCreator2); }; -
Martin, how do you use the tool
https://github.com/wix/wmlwhen creating a RN plugin?I know how!
React
in
const { navigationState, modalState, global: globalProps } = this.props; state => ({
modalState: state.modalState,
navigationState: state.navigationState,
global: state.global.toJS(),
}),but called as props.scene.navigationState.key
Answer:
Because it happens in functions like _renderScene(props) { ... where a parameter props is passed. It is not this.props. this.props will have the field this.props.nagivationState.
Proxipedia
-
Icon.jsdoes not processprops.name, but inButtonIcon.jsit is used as<Icon name={icon} />Callback function in Javascript. You have to check the definition of the
Itempackage. -
How much do we use immutable objects/arrays in the app, e.g.
pois.toJS()inHome.jscontainer?In reducers we work with javascript objects Redux store is immutable e.g. see util/redux/crud
changing immutability happens in
reducers+ inconnect, i.e. mapStateToProps -
What does
import { shallow } from 'enzyme';theshallowfunction do?shallowcreates a React component.—> write some tests
-
Where are the callbacks specified?
e.g. in
PoiDetail.jsin render function a prop of<Listview \>:renderSectionHeader={this._renderSectionHeader}and in the same file the function is defined as:
_renderSectionHeader = (data, section) => ( <View style={styles.sectionHeader}> <Text style={styles.sectionHeaderText}>{section}</Text> </View> );Where does
_renderSectionHeaderget its parameter values from? The same with_renderRow. It gets the media from somewhere, but from where?Answer
It is defined. The function
renderSectionHeaderexpects a callback with parameters(sectionData, sectionID), i.e. see React Native Documentation:renderSectionHeader function
(sectionData, sectionID) => renderable
If provided, a sticky header is rendered for this section. The sticky behavior means that it will scroll with the content at the top of the section until it reaches the top of the screen, at which point it will stick to the top until it is pushed off the screen by the next section header.
See redux docs for more infos
Open questions
- When is favourites index
-1? seefavoritesReducer. -
What is
util/react/coalesceNonElementChildren.js?—> Martin
-
What does
_computeSyntheticStateincomponents/Button/Button.jsdo?—> Martin
-
TODO: In
PoiDetail.js, who sendseventwhich is present in_renderStory()?It must be
onOpeninListItemStory. So iseventjust part of the genericComponent? -
ModalStack.jsis not visible initially —>left: 0, right: 0, bottom: 0, top: 0, -
TODO: in
BundleLoaderContainer.jsinvestigatemergeProps, i.e.what's the difference between `stateProps`, `dispatchProps` and `ownProps`? ```js // mergeProps(stateProps, dispatchProps, ownProps) => ({ progress: stateProps.progress, show: ownProps.show || stateProps.show, })
-
How does the following callback stuff work in
TourGrid.js?onDetailcallsonDetailand where is waypointId sent to<PoiGrid />?onDetail={(waypointId) => onDetail(waypoints.find((wp) => wp.id === waypointId).poi)}
Other
- Syntax: Why is
my_func() { ... }equivalent tomy_func: function() { ... }? Just syntactic sugar?
e.g. in Ember the model function here!
import Ember from 'ember';
export default Ember.Route.extend({
/*
model() {
let todos = [
{
title: "Learn Ember",
complete: false
},
{
title: "Solve World Hunger",
complete: false
}
];
return todos;
}
});Discuss on Twitter ● Improve this article: Edit on GitHub